Gawk output difference

Why the below option2 doesn't fetch similar output as option1 ? I am on linux.


$cat test
2013-01-01-00.25.43.643845

Option1:
cat test | gawk -F"-" ' {print $2 " " $3 " " $1}'
01 01 2013

Option2:
cat test | gawk '{FS="-"}  {print $2 " " $3 " " $1}'
2013-01-01-00.25.43.643845

In the second command the FS is set after reading the first record.

You have to change the field separator before you read the record or you have to force awk to re-evaluate the record to make the change in FS take effect. So, either of the following should work:

gawk 'BEGIN{FS="-"}  {print $2 " " $3 " " $1}' test

or
gawk '{FS="-";$1=$1} {print $2 " " $3 " " $1}' < test
Note that there is no need to use cat and a pipeline instead of the simple command letting awk open the file itself or using redirection in the shell to set the input file before kicking off awk.

Should be:

$0=$0

Thanks, that helps.

Was just wondering , if this thing is specific to GAWK 'coz nawk works fine on Solaris

$ cat test  | nawk '{FS="-"}  {print $2 " " $3 " " $1}' 
03 01 2013

Yes, different awk versions implement field splitting differently:

$ echo a:b | /usr/xpg4/bin/awk '{ FS = ":"; print NF }'
1
$ echo a:b | nawk '{ FS = ":"; print NF }'
2

That's why usually the correct way to assign a non-default field separator is in the BEGIN block or directly on the command line.

$ awk -F- '{ print $2, $3, $1 }' infile
01 01 2013
$ nawk -F- '{ print $2, $3, $1 }' infile
01 01 2013
$ /usr/xpg4/bin/awk -F- '{ print $2, $3, $1 }' infile
01 01 2013