Why does awk field assignment lose output separator?

This command is working. It displays a field separator (in this case, a comma):

$ echo "hi,ho"|awk -F, '/hi/{print $0}' hi,ho 

This command has strange output (comma missing):

 $ echo "hi,ho"|awk -F, '/hi/{$2="low";print $0}' hi low 

Setting the OFS variable (output field separator) to a comma fixes this case, but it really does not explain this behavior.

Can I say awk to save OFS?

+6
source share
3 answers

When changing the row ( $0 ), awk reconstructs all the columns and places the OFS value between them, which is the default space . You changed the value of $2 , which means that you forced awk revalue $0 .

When you print a line with $0 in the first case, since you did not change any fields, awk did not recount every field and, therefore, the field separator was saved.

To save the field separator, you can specify that with:

BEGIN block:

 $ echo "hi,ho" | awk 'BEGIN{FS=OFS=","}/hi/{$2="low";print $0}' hi,low 

Using the -v option:

 $ echo "hi,ho" | awk -F, -v OFS="," '/hi/{$2="low";print $0}' hi,low 

Definition at the end of awk :

 $ echo "hi,ho" | awk -F, '/hi/{$2="low";print $0}' OFS="," hi,low 
+10
source

You are the first example to not change anything, so everything prints out as an input.
In the second example, it changes the line and will use OFS by default, i.e. (one space)
To overcome this:

 echo "hi,ho"|awk -F, '/hi/{$2="low";print $0}' OFS="," hi,low 
+1
source

In your BEGIN action, set OFS = FS.

0
source

All Articles