Sed; insert text two lines above match

Hi!

Considering below text, how would I use sed to insert text right below the v0005-line, using the SEPARATOR-line as a pattern to search for, so two lines above the separator? I can do it right above the separator, but not 2 lines...

# v0004 - Some text
# v0005 - More text
#
######SEPARATOR#####

My goal is to insert another line, like so:

# v0004 - Some text
# v0005 - More text
# v0006 - New text
#
######SEPARATOR#####

Do you have to use sed? Easily done with ed. This is an edit inline example (editing the file itself).

ed file.txt <<EOF
/^######SEPARATOR#####
-2
a
# v0006 - New text
.
wq
EOF
1 Like

Hi,
not so efficient , but try this.

line_no=`awk END' { print NR-1 } ' file`
text="v0006 - New text"
sed ''"$line_no"'i'"# $text"'' file

Try also

awk '{B[NR%3]=$0} NR>2{ print B[(NR+1)%3]} /SEPARATOR/ {print "# v0006 - New text"}  END {print B[(NR+2)%3]; print B[(NR+3)%3]}' file1
# v0004 - Some text
# v0005 - More text
# v0006 - New text
#
######SEPARATOR#####

Hi All!
Thanks for the replies! I'm afraid I wasn't clear enough in my initial example. I realized that when I received my first reply, but I wasn't able to reply anymore.

The separator is NOT the last line in the file, I want to automatically insert a line into an existing changelog, that is part of a script, which starts below the separator...
I would like to use the separator, because sometimes the comments in the changelog span multiple lines, so I can't look for the last v000x and append a new line below it.

Like so:

# v0004 - Some text
# v0005 - More text
# v0006 - New text
#
######SEPARATOR#####
Script start here...

---------- Post updated at 10:39 AM ---------- Previous update was at 10:33 AM ----------

Never mind. RudiC's piece of code, even though it's completely incomprehensible, does the job!

awk '
                {B[NR%3]=$0}                    # use a circular 3 line buffer (B array) for delayed printing
NR>2            {print B[(NR+1)%3]}             # from line three, print line No. - 2 (acquaint yourself with the "%" modulo function)
/SEPARATOR/     {print "# v0006 - New text"}    # if the search string is found, print the text after the text of 2 lines ago
END             {print B[(NR+2)%3]              # just empty the buffer when input is done
                 print B[(NR+3)%3]
                }
' file
1 Like