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 ?
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