How can I copy the content of a text file and paste it to another starting at a certain line?
The easiest tool here might be sed
. To insert b.txt
into a.txt
after the 5th line , you could write:
sed '5r b.txt' a.txt
sed
reads the file specifiied as argument (a.txt
) line by line. All lines get reproduced in the output just as they appeared in the input, unless they get altered by a command.
The 5
is an address (line number) at which the following command shall be executed. The command we use is r
, which takes a file name as argument (here b.txt
), reads it completely and inserts it into the output after the current line.
As it stands above, this sed
command line will only print the output to the terminal, without writing to any files. You can either redirect it to a new file (not any of the input files!) using Bash's output redirection:
sed '5r b.txt' a.txt > c.txt
Or you can directly modify the outer input file a.txt
by using sed
's -i
(for "in-place") switch. If you write it as -i.bak
, it will make a backup copy of the original input file with the suffix .bak
first:
sed -i '5r b.txt' a.txt
An example:
$ cat a.txt
January
February
March
April
May
October
November
December
$ cat b.txt
June
July
August
September
$ sed '5r b.txt' a.txt
January
February
March
April
May
June
July
August
September
October
November
December
head
and tail
solution
Assume the source file is called ~/a
and the file to be inserted is called ~/b
. We'll put the merged file into ~/c
:
head -n 5 ~/a > ~/c
cat ~/b >> ~/c
tail --lines=+6 ~/a >> ~/c
- The path
~/
is short hand for your/home/user
directory name - head copies the first five lines of file
a
into newly created filec
- cat lists the contents of file
b
and appends it to filec
- tail appends file
a
starting at line 6 until the end to filec
After verification rename merged file
After verifying that file c
is merged correctly from files a
and b
we'll rename c
to a
using:
mv ~/c ~/a
-
mv
moves filec
into filea
. Data isn't physically moved. The file is simply renamed which saves time.