问题
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?
回答1:
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
回答2:
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
.
来源:https://stackoverflow.com/questions/41313608/how-to-append-to-the-lines-with-fewer-columns-in-a-tab-separated-text-file