bash cut columns to one file and save onto the end of another file

丶灬走出姿态 提交于 2021-02-07 13:24:42

问题


I would like to cut two columns from one file and stick them on the end of a second file. The two file have the exact same number of lines

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

So far I have been using

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

which outputs exactly what I want

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

However I don't want to have to make a new file I would prefer to alter file 1 to the above. I've tried

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

but it simply prints everything on screen. Is there a way of just adding columns 9 and 10 to the end of file1.txt?


回答1:


Use sponge from moreutils! It allows you to soak up standard input and write to a file. That is, to replace a file in-place after a pipe.

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

Note you can also do what you are doing by using paste with a process 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

This joins file1.txt with two last columns from file2.txt using ' ' as delimiter.



来源:https://stackoverflow.com/questions/30927999/bash-cut-columns-to-one-file-and-save-onto-the-end-of-another-file

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