How to append to the lines with fewer columns in a tab separated text file?

77 views Asked by At

I have a tab separated text file. Some rows have 10 columns and some rows have 11 columns. I want to add an extra column to the last of 10 column rows with the value 0. How can i do this?

2

There are 2 answers

19
Inian On BEST ANSWER

Since you have mentioned append, you can awk as below

awk -F $'\t' 'BEGIN {OFS = FS} NF==10{$0=$0"0"}1' input-file

The -F $'\t' takes care of the tab-separation part, BEGIN {OFS = FS} for setting the output field separation.

The NF==10 looks only for the lines having only 10 records and the {$0=$0"0"}1 for reconstructing that line with the extra word added.

To write to a separate file use the > redirect operator as

awk -F $'\t' 'BEGIN {OFS = FS} NF==10{$0=$0"0"}1' input-file > output-file

To replace the original file use mv

awk -F $'\t' 'BEGIN {OFS = FS} NF==10{$0=$0"0"}1' input-file > output-file ; mv output-file input-file

Or if you have latest GNU Awk (since 4.1.0 released), it has the option of "inplace" file editing:

gawk -i inplace -F $'\t' 'BEGIN {OFS = FS} NF==10{$0=$0"0"}1' input-file
0
potong On

This might work for you (GNU sed):

sed -r 's/[^\t]+/&/11;t;s/$/\t0/' file

This replaces the eleventh column with itsself otherwise it adds a tab and then 0.