Why is OFS not working?

$ echo "a b c" | awk 'BEGIN {OFS=","}; {print $0};' -
a b c

I tried to see if applied OFSafter the last field, so expecting the output to be either

a,b,c

or

a,b,c,

but the change OFSdoes not work. Why?

+4
source share
2 answers

You must change / set the field so that it $0will be recounted, then it will be applied OFS. For example.

echo "a b c" | awk 'BEGIN {OFS=","}; {$1=$1;print $0};'
+5
source

$ 0 does not change, assigning OFS. However, $ 0 changes when assigned to any of its elements, including any non-existent fields.

echo "ab c" | awk 'BEGIN {OFS = ","}; {$ 4 = ""; print $ 0}; -

gives: a, b, c,

+1
source

Source: https://habr.com/ru/post/1623492/


All Articles