PDA

View Full Version : [SOLVED] awk : why do these two give a different o/p for the first line ?



IAMTubby
May 16th, 2014, 08:46 AM
Hello,
This question is regarding using the FS (Field separator) option in awk

Why is the output different for the below commands,
1. IAMTubby@IAMTubby-Inspiron-1545:~/Desktop$ head -n 2 /etc/passwd | awk 'BEGIN{FS=":"}{OFS="--";print $1, $2}'
0--0--root
1--1--daemon


2.IAMTubby@IAMTubby-Inspiron-1545:~/Desktop$ head -n 2 /etc/passwd | awk '{FS=":";OFS="--"; print $3, $4, $5}'
----
1--1--daemon

According to me, the first output is what I'm looking for and the second output is incorrect.
My question is, why isn't the FS=":" taken into account for the first line of /etc/passwd in 2 above ?
Doesn't everything inside the action block {} run for EVERY line ?

Thanks.

spjackson
May 16th, 2014, 09:04 AM
In the 2nd case, on line 1 of input, the line has been parsed and $3, $4, $5 assigned before you enter the action block, i.e. before you assign FS. You need to do the assignment in a BEGIN block, e.g.


head -n 2 /etc/passwd | awk 'BEGIN {FS=":";OFS="--";} {print $3, $4, $5}'

IAMTubby
May 17th, 2014, 08:19 AM
In the 2nd case, on line 1 of input, the line has been parsed and $3, $4, $5 assigned before you enter the action block, i.e. before you assign FS. You need to do the assignment in a BEGIN block, e.g.
Thanks spjackson. Shall follow assignment inside the BEGIN block.