Reputation: 5992
Why does the following happen? How can I understand the logic?
$ echo "123456" | awk 'BEGIN {FS="4"; OFS="-"}; {print}'
123456
But if I "modify" some of the fields, everything is OK:
$ echo "123456" | awk 'BEGIN {FS="4"; OFS="-"}; {$1=$1;print}'
123-56
Upvotes: 1
Views: 88
Reputation: 74596
The Output Field Separator only takes effect once record has been touched in some way. From the GNU AWK manual:
It is important to remember that
$0
is the full record, exactly as it was read from the input. This includes any leading or trailing whitespace, and the exact whitespace (or other characters) that separates the fields.It is a common error to try to change the field separators in a record simply by setting FS and OFS, and then expecting a plain
print $0
to print the modified record.But this does not work, because nothing was done to change the record itself. Instead, you must force the record to be rebuilt, typically with a statement such as
$1 = $1
Upvotes: 2