Insert multiple lines of text before a specific line using Bash

I try to insert a few lines of text before a specific line, but keep getting sed errors when I try to add a new line character. My command looks like this:

sed -r -i '/Line to insert after/ i Line one to insert \\ second new line to insert \\ third new line to insert' /etc/directory/somefile.txt 

The error is reported:

 sed: -e expression #1, char 77: unterminated `s' command 

I tried using \n , \\ (as in the example) no character at all, just moving the second line to the next line. I also tried something like:

 sed -r -i -e '/Line to insert after/ i Line one to insert' -e 'second new line to insert' -e 'third new line to insert' /etc/directory/somefile.txt 

EDIT !: Apologies, I wanted the text to be inserted before the existing one, and not after!

+6
source share
6 answers

This should work:

 sed -i '/Line to insert after/ i Line one to insert \ second new line to insert \ third new line to insert' file 
+8
source

For anything other than simple substitutions on separate lines, use awk instead of sed for simplicity, clarity, reliability, etc. etc.

Insert before line:

 awk ' /Line to insert before/ { print "Line one to insert" print "second new line to insert" print "third new line to insert" } { print } ' /etc/directory/somefile.txt 

Insert after line:

 awk ' { print } /Line to insert after/ { print "Line one to insert" print "second new line to insert" print "third new line to insert" } ' /etc/directory/somefile.txt 
+4
source
 sed -i '/Line to insert after/ i\ Line one to insert\ second new line to insert\ third new line to insert' /etc/directory/somefile.txt 
0
source

This may work for you (GNU sed and Bash):

 sed -i $'/Line to insert after/a\line1\\nline2\\nline3' file 
0
source

This ll works from the first line .. For example: If you want to insert from the third line of the file, replace "1i" with "3i".

 sed -i '1i line1'\\n'line2'\\n'line3' 1.txt cat 1.txt line1 line2 line3 Hai 
0
source

To be POSIX compatible and work on OS X, I used the following (a single quote and an empty string for demo purposes):

 sed -i "" "/[pattern]/i\\ line 1\\ line 2\\ \'line 3 with single quotes\` \\ " <filename> 
0
source

All Articles