Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
164 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since you have mentioned append, you can awk as below

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

The -F $' ' 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 $'	' 'BEGIN {OFS = FS} NF==10{$0=$0"0"}1' input-file > output-file

To replace the original file use mv

awk -F $'	' '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 $'	' 'BEGIN {OFS = FS} NF==10{$0=$0"0"}1' input-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...