sed insert text 2 lines above pattern

Hi

I am trying to insert a block of text 2 lines above a pattern match using sed

eg

#Start of file entry
{

}
#End of file entry

new bit of text has to be put in just above the } eg

#Start of file entry
{

New bit of text
}
#End of file entry

I have tried the

sed /Pattern/i "text" filename

but it keeps getting garbled with the \n

Hi,

Try this one,

awk -v pat="}" '{a[NR]=$0;}END{for(i=1;i<=NR;i++){if(a ~ pat ){print "Insert Block\n"a;}else{print a;}}}' file

Cheers,
Ranga:)

Try:

sed '/}/i\
New bit of text\
' infile
awk '/}/{print "New bit of text"}1' infile

Hi rangarasan

thanks for that but I'm a bit confused not that used to awk

is pattern my pattern match eg

/\}\/n#End of file entry 1/

or is this the block of text I want to insert and how will this handle multiple inserts depending in the Start and End value eg in a file like test.txt

#Start of file entry 1
{
Insert text block a
}
#End of file entry 1
#Start of file entry 2
{
Insert of text block b
}
#End of file entry 2

If } found then we need add some part before "}" line right?
If Yes, check with the awk else provides us desired input and desired output.

Hi

its more if

#End of file entry 1

is found then insert the text before the } above it

I have tried the following but it returns nothing

sed -e 's/\}\n#End of file entry 1/#Start of Range\n range 123.456.789.0\n\}#End of file entry 1/' test

Sed can not be used to operate beyond newlines like that... Try:

sed '/}/{N;/\n#End of file entry 1/{s/^/text to insert\
/;};}' infile

or more modern sed:

sed '/}/{N;/\n#End of file entry 1/{s/^/text to insert\n/;};}' infile

Thanks for that guys, I was still having problems with adding in new lines in the inserted text so I came up with the following which does what I need

cat test.sed | /usr/xpg4/bin/sed -n -e '1h;1\!H;${;g;s/}.*#END OF/#START OF RANGE\;}\;#END OF/g;p;}' | tr \; \\

---------- Post updated at 09:42 AM ---------- Previous update was at 09:41 AM ----------

oops last buit of tr should be \\n for newline