Insert multiple lines into a file after specified pattern using shell script

I want to insert multiple lines into a file using shell script. Let us consider my input file contents are: input.txt:

abcd
accd
cdef
line
web

Now I have to insert four lines after the line 'cdef' in the input.txt file. After inserting my file should change like this:

abcd
accd
cdef
line1
line2
line3
line4
line
web

The above insertion I should do using the shell script. Can any one help me?


Another sed,

sed '/cdef/r add.txt' input.txt

input.txt:

abcd
accd
cdef
line
web

add.txt:

line1
line2
line3
line4

Test:

sat:~# sed '/cdef/r add.txt' input.txt
abcd
accd
cdef
line1
line2
line3
line4
line
web

If you want to apply the changes in input.txt file. Then, use -i with sed.

sed -i '/cdef/r add.txt' input.txt

If you want to use a regex as an expression you have to use the -E tag with sed.

sed -E '/RegexPattern/r add.txt' input.txt

Using GNU sed:

sed "/cdef/aline1\nline2\nline3\nline4" input.txt

If you started with:

abcd
accd
cdef
line
web

this would produce:

abcd
accd
cdef
line1
line2
line3
line4
line
web

If you want to save the changes to the file in-place, say:

sed -i "/cdef/aline1\nline2\nline3\nline4" input.txt

sed '/^cdef$/r'<(
    echo "line1"
    echo "line2"
    echo "line3"
    echo "line4"
) -i -- input.txt

Using awk:

awk '/cdef/{print $0 RS "line1" RS "line2" RS "line3" RS "line4";next}1' input.txt 

Explanation:

  • You find the line you want to insert from using /.../
  • You print the current line using print $0
  • RS is built-in awk variable that is by default set to new-line.
  • You add new lines separated by this variable
  • 1 at the end results in printing of every other lines. Using next before it allows us to prevent the current line since you have already printed it using print $0.

$ awk '/cdef/{print $0 RS "line1" RS "line2" RS "line3" RS "line4";next}1' input.txt
abcd
accd
cdef
line1
line2
line3
line4
line
web

To make changes to the file you can do:

awk '...' input.txt > tmp && mv tmp input.txt