I've reformatted the awk
code:
for(i=1;i<=NF;i++)
if($i~/-f/)
print $(i+1)
The for-loop iterates from 1 to NF
, the number of fields in any input line.
Each field ($i
) in the input line gets checked to see if it matches the pattern "-f", which is just a string literal.
If a field matches "-f", then the code prints out the field following the field that contains "-f".
On my a RHEL box, this ends up printing out:
/www/csbe-int-fb-na/generated/httpd.conf -C
If you look closely at the input line, there's a field that consists exactly of "-f", and indeed, awk
prints out the next field, "/www/csbe-int-fb-na/generated/httpd.conf" Confusingly, that field contains an embedded "-f", so on the next iteration of the for-loop, the awk
script finds taht "/www/csbe-int-fb-na/generated/httpd.conf" contains "-f", so it prints the next field, "-C".
If all you want is the Apache configuration file, you can modify the pattern that the field must match to make it an exact match, and have the awk
script quit after finding the "-f" field, and printing the next field.
awk '{for(i=1;i<=NF;i++)if($i~/^-f$/) {print $(i+1); exit} }'
line1
, but the example code hasecho $line
. You need to use consistent variable naming. – Dec 15 '15 at 16:50echo $line
, correct? – Dec 15 '15 at 19:01echo "$line1"
. Also you should add double quotes around the whole command substitution:"$(echo "$line1" | awk '...')"
See http://unix.stackexchange.com/a/131767/135943 – Wildcard Dec 15 '15 at 21:39$i~/^-f$/
could be made clearer as$i == "-f"
– Gilles 'SO- stop being evil' Dec 15 '15 at 22:47