Bootsector Bootsector - 1 month ago 4
Linux Question

How to remove lines before the keyword and up to its match string tag

I have a file like this:

Sample text1 <TAG> some text
Line1
Line2
<INSERT>
Sample text3 <TAG> some text
Line3
<DELETE>
Sample text4 <TAG> some text
Line4
Line5
<INSERT>
Sample text5 <TAG> some text
Line6
<DELETE>


I want to remove the lines before the DELETE and up to the TAG so that it will look like this:

Sample text1 <TAG> some text
Line1
Line2
<INSERT>
Sample text4 <TAG> some text
Line4
Line5
<INSERT>

Answer

In awk using my previous solution mentioned in comments:

$ cat foo.awk
/TAG/ { printf "%s", b; b="" }                       # at START output buffer and empty it
{ b=b $0 ORS }                                       # gather buffer
/DELETE/ { b="" }                                    # at empty buffer at END also

Run it:

$ awk -f foo.awk foo2
Sample text1 <TAG> some text
Line1
Line2
<INSERT>
Sample text4 <TAG> some text
Line4
Line5
<INSERT>