Reputation: 4830
This command works. It outputs the field separator (in this case, a comma):
$ echo "hi,ho"|awk -F, '/hi/{print $0}'
hi,ho
This command has strange output (it is missing the comma):
$ echo "hi,ho"|awk -F, '/hi/{$2="low";print $0}'
hi low
Setting the OFS
(output field separator) variable to a comma fixes this case, but it really does not explain this behaviour.
Can I tell awk
to keep the OFS?
Upvotes: 7
Views: 4436
Reputation: 41456
You first example does not change anything, so all is printed out as the input.
In second example, it change the line and it will use the default OFS, that is (one space)
So to overcome this:
echo "hi,ho"|awk -F, '/hi/{$2="low";print $0}' OFS=","
hi,low
Upvotes: 1
Reputation: 77105
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
Upvotes: 11