Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 320
catcha Avatar asked Jun 19 '15 00:06

catcha


1 Answers

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.

like image 96
fedorqui 'SO stop harming' Avatar answered Oct 21 '22 08:10

fedorqui 'SO stop harming'