Paul
Paul

Reputation: 696

Stop AWK from replacing tabs with spaces

I am trying to modify the first character of each line in a file separated by both spaces and tabs.

In the following example the first 3 spaces are tabs and the following two spaces are spaces.

cat example.gtf
1      havana  gene    11896 14409 .
1      havana  gene    12613 12227 .

I want to prepend an m to the first value in each row as in the following... desired output.gtf. This can be achieved with awk '$1="m"$1' example.gtf > desiredOutput.gtf

cat desiredOutput.gtf
m1      havana  gene    11896 14409 .
m1      havana  gene    12613 12227 .

However, awk replaces the first three tabs with spaces, corrupting the format of the output file. How can I prevent awk from changing tabs to spaces?

Upvotes: 0

Views: 519

Answers (2)

Ed Morton
Ed Morton

Reputation: 203189

$ cat file
1       havana  gene    11896 14409 .
1       havana  gene    12613 12227 .

In decreasing order of simplicity, clarity, and performance:

$ awk '{print "m"$0}' file
m1      havana  gene    11896 14409 .
m1      havana  gene    12613 12227 .

$ awk '{$0="m"$0} 1' file
m1      havana  gene    11896 14409 .
m1      havana  gene    12613 12227 .

$ awk 'BEGIN{FS=OFS="\t"} {$1="m"$1} 1' file
m1      havana  gene    11896 14409 .
m1      havana  gene    12613 12227 .

Upvotes: 3

Jotne
Jotne

Reputation: 41446

Simple SED

sed 's/^/m/g' file
m1      havana  gene    11896 14409 .
m1      havana  gene    12613 12227 .

Upvotes: 2

Related Questions