4

I use awk gsub to replace a string in a specific column of my tab-separated file:

cat test.txt 
1   1   2032    1
2   1   2032    2
3   1   999 3
4   1   2032    4
5   1   9999    5

However, the modified line is separated by spaces, even if -F "\t" was specified:

awk -F "\t" '{gsub(/^999$/,"XXX",$3);print}' test.txt
1   1   2032    1
2   1   2032    2
3 1 XXX 3
4   1   2032    4
5   1   9999    5

How can I have the modified line(s) separated by tabs as well ?

Sébastien Clément
  • 570
  • 1
  • 9
  • 19

1 Answers1

5

You should set

OFS="\t"

so :

awk -F "\t" '{gsub(/^999$/, "XXX", $3); print}' OFS="\t" test.txt

or

awk -F "\t" -v OFS="\t" '{gsub(/^999$/, "XXX", $3); print}' test.txt

or

awk 'BEGIN{OFS=FS="\t"}{gsub(/^999$/, "XXX", $3); print}' OFS="\t" test.txt

See man awk

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
  • I took this to mean set an environment variable `OFS="\t"`, which did not work for me. I should have read more closely. – tremby Oct 31 '14 at 21:07