0

Can some one explain what the awk '{for(i=1;i<=NF;i++) if($i~/-f/) print $(i+1)}') part does in the following snippet

line='/wwws/apache/apache2.4.16w-r01/instroot/bin/httpd -f /www/csbe-int-fb-na/generated/httpd.conf -C ServerName int-b2vusii.bmwgroup.net -c PidFile /var/tmp/apache_csbe-int-fb-na/httpd.pid'
CONF=$(echo $line | awk '{for(i=1;i<=NF;i++) if($i~/-f/) print $(i+1)}')

O/p : /www/csbe-int-fb-na/generated/httpd.conf -C

but i need to get only /www/csbe-int-fb-na/generated/httpd.conf

robotTech
  • 35
  • 7

1 Answers1

4

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} }'
  • Thanks for the explanation but the same is not getting applied in the below case "line1='/wwws/apache/apache2.4.16w-r01/instroot/bin/httpd -f /www/nop-admin-web/generated/httpd.conf -C ServerName nop-admin-us-int.bmwgroup.net -c PidFile /var/tmp/apac he_nop-admin-web/httpd.pid' CONF=$(echo $line | awk '{for(i=1;i<=NF;i++) if($i~/-f/) print $(i+1)}') " O/P : /www/nop-admin-web/generated/httpd.conf – robotTech Dec 15 '15 at 16:44
  • @VinayThupili - You set a value of line1, but the example code has echo $line. You need to use consistent variable naming. –  Dec 15 '15 at 16:50
  • Sorry it was "CONF=$(echo $line1 | awk '{for(i=1;i<=NF;i++) if($i~/-f/) print $(i+1)}')" – robotTech Dec 15 '15 at 17:11
  • @VinayThupili - so if works once you do echo $line, correct? –  Dec 15 '15 at 19:01
  • @VinayThupili, add double quotes around the variable: echo "$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
  • 1
    $i~/^-f$/ could be made clearer as $i == "-f" – Gilles 'SO- stop being evil' Dec 15 '15 at 22:47