How to insert multiple lines with sed

I want to add this

#this 
##is my 
text

before the line

the specific line 

I tried this

sed -i '/the specific line/i \
#this 
##is my 
text
' text.txt

but it only adds in 'text'.

I also tried various combinations with \ and " " but nothing worked.


You're missing the trailing backslash at the end of some lines (and you have an eccessive newline at the end of the last line you want to insert):

sed -i '/the specific line/i \
#this\
##is my\
text' file
% cat file
foo
the specific line
bar

% sed -i '/the specific line/i \
#this\
##is my\
text' file

% cat file
foo
#this 
##is my 
text
the specific line
bar

With newlines:

% sed -i '/the specific line/i #this\n##is my\ntext' foo

% cat foo
#this
##is my
text
the specific line

When the replacement string has newlines and spaces, you can use something else. We will try to insert the output of ls -l in the middle of some template file.

awk 'NR==FNR {a[NR]=$0;next}
    /Insert index here/ {for (i=1; i <= length(a); i++) { print a[i] }}
    {print}'
    <(ls -l) text.txt

When you want something inserted after a line, you can move the command {print} or switch to :

sed '/Insert command output after this line/r'<(ls -l) text.txt

You can also use sed for inserting before a line with

sed 's/Insert command output after this line/ls -l; echo "&"/e' text.txt