Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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

In your BEGIN action, set OFS = FS.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top