Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't OFS work?

Tags:

awk

$ 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?

like image 964
Tim Avatar asked Mar 10 '26 00:03

Tim


2 Answers

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};'
like image 118
Kent Avatar answered Mar 11 '26 21:03

Kent


{ 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.

like image 42
Kemin Zhou Avatar answered Mar 11 '26 21:03

Kemin Zhou



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!