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

孤街醉人 提交于 2019-12-13 08:19:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!