With an array of elements, and an input-file I want to loop through the array and match each element with the input-file. I then want to get the line in the input-file where this element is occurring and the 3 lines that follows directly beneath. I have tried doing it this way:
for variable in $array
do
awk -v var="$variable" '/var/{x=NR+3}(NR<=x){print}' inputfile.txt
done
But this did not return the desired out put. I then tried grep:
for variable in $array
do
grep -A 3 "$variable" inputfile.txt
done
And this works. I guess I solved my problem, but as I would like to get a better understanding of awk, I decided to post this question, as I am curious to know what I am doing wrong when I try and feed awk a variable. I think I might be confused because the awk piece I have picked up, is without a BEGIN part? I am guessing a BEGIN part is assumed , and not necessary? Can my problem be solved with awk? Is awk the best tool for this task? And can my awk example be rewritten to have a BEGIN and END section, so it matches the examples and tutorials in awk I have looked at elsewhere on the internet? Thanks
BEGIN
; it won't work without it. – Alex Aug 22 '17 at 20:18BEGIN
, and it started working normally. I guess it depends on the system? – Alex Aug 23 '17 at 13:19BEGIN
andEND
. If you look at theawk
man page, you'll see that it supports several statements (e.g.,if
,for
,print
, andwhile
) and many functions (e.g.,gsub
,index
,length
, andmatch
). You don’t need to use them all; you just use the ones you need. It’s true that, ifBEGIN
andEND
are not specified, they are assumed — to be null. It seems to me that you're making this more complicated than it is. P.S. You (sku2003) might get better support if you posted example data for which RomanPerekhrest’s answer doesn’t work. – Scott - Слава Україні Aug 26 '17 at 03:50