Mathews Jose Mathews Jose - 6 months ago 11
Bash Question

Bash : How to insert a block of text after a certain line into a file in Unix?

I have a file file1.txt like below :

line 1 file 1
line 2 file 1
line 3 file 1
line 4 file 1


And a second file file2.txt like below :

line 1 file 2
line 2 file 2
line 3 file 2
line 4 file 2
line 5 file 2


I want to right a one line command (preferably with sed ) that will get the lines 2-4 from second file (file2.txt) and add those lines after line 3 into the first file(file1.txt) .

So my output should be like below :

line 1 file 1
line 2 file 1
line 3 file 1
line 2 file 2
line 3 file 2
line 4 file 2
line 4 file 1


For getting the lines 2-4 from second file i could use :

sed -n '2,4p' file2.txt


And for inserting the lines after line 3 in file 1 i could use like below :

sed '4i<What to insert here>' file1.txt


But how to combine both these operations ?

Answer

Agreeing with the other answerer that this is a job for awk, it can be done with sed.

sed offers all kind of strange commands besides the famous s command and there is a e execute command for GNU sed. After you have given all the pieces in the question, here is how to combine your ideas:

sed '4 e sed -n 2,4p file2.txt' file1.txt