When you modify the line ($0
) awk
re-constructs all columns and puts the value of OFS
between them which by default is space. You modified the value of $2
which means you forced awk
to re-evaluate$0
.
When you print the line as is using $0
in your first case, since you did not modify any fields, awk
did not re-evaluated each field and hence the field separator is preserved.
In order to preserve the field separator, you can specify that using:
BEGIN
block:
$ echo "hi,ho" | awk 'BEGIN{FS=OFS=","}/hi/{$2="low";print $0}'
hi,low
Using -v
option:
$ echo "hi,ho" | awk -F, -v OFS="," '/hi/{$2="low";print $0}'
hi,low
Defining at the end of awk
:
$ echo "hi,ho" | awk -F, '/hi/{$2="low";print $0}' OFS=","
hi,low