bash 如何将一列从一个文件添加到另一个文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17095306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add a column from a file to another file
提问by Valerio D. Ciotti
I have a file with two columns as
我有一个包含两列的文件
1 1
2 3
3 4
and a file with one column as
和一个包含一列的文件
6
7
9
I would like to add the second file in the first one. The output should be:
我想在第一个文件中添加第二个文件。输出应该是:
1 1 6
2 3 7
3 4 9
回答by Chris Seymour
$ pr -mts' ' file1 file2
1 1 6
2 3 7
3 4 9
$ paste -d' ' file1 file2
1 1 6
2 3 7
3 4 9
回答by jaypal singh
awk 'NR==FNR{a[NR]=awk 'NR==FNR{a[++y]=exec 3<twofile
while read x; do read -u 3 y; echo $x $y; done <onefile
;next}{b[++x]=cat >onefile <<XXX
1 1
2 3
3 4
XXX
cat >twofile <<XXX
6
7
9
XXX
}
END{z=x>y?x:y;while(++i<=z){print a[i],b[i]}}' file1 file2
;next}{print a[FNR],1 1 6
2 3 7
3 4 9
}' file1 file2
Note:Will work with files of same length. If file lengths' are different, go with sudo_O'ssolution.
注意:适用于相同长度的文件。如果文件长度不同,请使用sudo_O 的解决方案。
Just for the heck of it, here is an awk
command that I think should simulate paste
. Purely for fun though, if I were you I would still go with sudo_O'ssolution (or may be not!)
只是为了它,这是一个awk
我认为应该模拟的命令paste
。不过纯粹是为了好玩,如果我是你,我仍然会使用sudo_O 的解决方案(或者可能不会!)