1

This is just for curiosity.

I have a tab delimited file like this

jklh    banana  hk
hkl klh jklh
h   hk  banana
h   hk  kljh
asdf    banana  lk
sdfa    jklæ    jklæ
banana  sdf jklæ

By doing this I replace 'banana' in the first column and the output stays otherwise the same:

awk '{gsub(/banana/,0,$1)}; {printf "%s\t%s\t%s\n", $1, $2, $3}' file > outfile

This on the other hand replaces tabs with spaces in the line I replaced the word banana with 0:

awk '{gsub(/banana/,0,$1)}; {print}' file > outfile

How can I use OFS or something similar to print out the replaced line without replacing tabs. I've been playing around alot without progress. Remember: No printf

AWE
  • 4,045
  • 9
  • 33
  • 42

1 Answers1

2

Set OFS to a tab:

awk -v OFS="\t" '{gsub(/banana/,0,$1)}; {print}'
AWE
  • 4,045
  • 9
  • 33
  • 42
Michael J. Barber
  • 24,518
  • 9
  • 68
  • 88
  • 2
    @AWE: Alternatives: You can use it without the `-v` by putting it at the end: `awk '{...}' OFS="\t" inputfile` or in a `BEGIN` block: `awk 'BEGIN {OFS = "\t"} {...}' inputfile` – Dennis Williamson May 14 '12 at 12:15
  • Somehow I didn't stumble on any of the right alternatives when I was trying. I see now I was often close. – AWE May 14 '12 at 12:24