【问题标题】:bash cut columns to one file and save onto the end of another filebash 将列剪切到一个文件并保存到另一个文件的末尾
【发布时间】:2015-06-19 00:19:51
【问题描述】:

我想从一个文件中剪下两列并将它们粘贴到第二个文件的末尾。这两个文件的行数完全相同

file1.txt
1  2  3  4  5  6  7  8  9  10  
1  2  3  4  5  6  7  8  9  10
1  2  3  4  5  6  7  8  9  10

file2.txt
a  b  c  d  e  f  g  h i  j
a  b  c  d  e  f  g  h i  j
a  b  c  d  e  f  g  h i  j
a  b  c  d  e  f  g  h i  j

到目前为止我一直在使用

cut -f9-10 file2.txt  | paste file1.txt - > file3.txt

输出的正是我想要的

1  2  3  4  5  6  7  8  9  10  i  j
1  2  3  4  5  6  7  8  9  10  i  j
1  2  3  4  5  6  7  8  9  10  i  j

但是我不想创建一个新文件,我希望将文件 1 更改为上述文件。我试过了

cut -f9-10 file2.txt  | paste file1.txt -

但它只是在屏幕上打印所有内容。有没有办法只将第 9 列和第 10 列添加到 file1.txt 的末尾?

【问题讨论】:

  • 请注意,您提到这两个文件的行数相同,而第二个文件多一个。

标签: linux bash paste cut


【解决方案1】:

使用moreutils 中的sponge!它允许您soak up standard input and write to a file。也就是说,在管道之后就地替换文件。

cut -f9-10 file2.txt  | paste file1.txt - | sponge file1.txt

请注意,您也可以通过使用 pasteprocess substitution 来执行您正在执行的操作。

$ paste -d' ' file1.txt <(awk '{print $(NF-1), $NF}' file2.txt) | sponge file1.txt
$ cat file1.txt
1  2  3  4  5  6  7  8  9  10 i j
1  2  3  4  5  6  7  8  9  10 i j
1  2  3  4  5  6  7  8  9  10 i j

这将file1.txtfile2.txt 的最后两列连接起来,使用' ' 作为分隔符。

【讨论】:

  • 这是一个比我发布的解决方案更好的解决方案,所以我删除了我的解决方案并投票赞成这个解决方案。
  • 谢谢@MikeAtkins :) 我做了一些研究,发现了这个spongethingy。它看起来像工具!
猜你喜欢
  • 2017-07-08
  • 1970-01-01
  • 1970-01-01
  • 2022-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多