Linux to add data from one file to another

How to transfer data from file1.txt to file2.txt?

+6
source share
4 answers

The following command will take two files and merge them into one

cat file1.txt file2.txt > file3.txt; mv file3.txt file2.txt 
+6
source

You can do this in the pipeline using sponge from moreutils :

 cat file1.txt file2.txt | sponge file2.txt 
+5
source

Another way to use GNU sed:

 sed -i -e '1rfile1.txt' -e '1{h;d}' -e '2{x;G}' file2.txt 

I.e:

  • On line 1, add the contents of file1.txt
  • In line 1, copy the template space to save a space, and delete the template space
  • On line 2, exchange the contents of the hold space and the template and add the hold space to the drawing space

The reason is a bit complicated because the r command adds content and line 0 is not addressed, so we must do this on line 1 by moving the contents of the original line to the side and then returning it after adding the contents of the file.

+3
source

The way to write a file is similar to 1). add at the end of the file or 2). overwrite this file.

If you want to put content in file1.txt before file2.txt, I'm afraid you need to rewrite the combined penalty.

0
source

Source: https://habr.com/ru/post/919269/


All Articles