I am beginning to learn awk
and came across something that when I run the following commands
$ echo ":a:b:c:" | awk '$1=$1' FS=":" OFS="$"
$ echo "a:b:c:" | awk '$1=$1' FS=":" OFS="$"
a$b$c$
First command returns nothing, but I expected it to return $a$b$c$
, similar to the second command. And in general, it never prints anything when the field separator is at the beginning of the line. Why so?
Best Answer
In your
awk
script, printing is triggered as the default action, which in turn depends on "side-effect" evaluation of assignment$1=$1
as a pattern.In the first case, there is an empty field before the first separator, so
$1
is the empty string, which evaluates FALSE. In the second case,$1
is the non-empty stringa
, which evaluates TRUE, triggering the default print action.