Reputation: 99428
$ echo "a b c" | awk 'BEGIN {OFS=","}; {print $0};' -
a b c
I was trying to see if OFS
applies after the last field, so expecting the output to be either
a,b,c
or
a,b,c,
but the change of OFS
doesn't work. Why is it?
Upvotes: 12
Views: 5515
Reputation: 6891
{ print $1, $2, $3 } will use the OFS value regardless of any fields got updated or not. But this solution is not portable. I am hoping other better solutions such as print $WITH_OFS that may be a new feature of AWK.
Upvotes: 4
Reputation: 5939
$0 is not modified by assigning to OFS. $0, however, gets modified when you assign to any of its elements, including any non-existing fields.
echo "a b c" | awk 'BEGIN {OFS=","}; {$4="";print $0};' -
gives: a,b,c,
Upvotes: 2
Reputation: 195059
You should change/set a field, so that the $0
is recomputed, then OFS
will be applied. E.g.
echo "a b c" | awk 'BEGIN {OFS=","}; {$1=$1;print $0};'
Upvotes: 14