Search code examples
awkgawkseparator

awk to take FS into effect


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

Solution

  • 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 or 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