Removing text from pattern1 up to and including 2nd match of pattern2

awksedtext processing

I have a text file like so:

<!--START OF FILE -->
random text
<meta> more random text </meta>
x x x x x x x 
more random text
that I dont need 
x x x x x x x

I need everything
from this point
onwards
...

I need to remove everything between <!--START OF FILE --> and the second
x x x x x x x like so:

I need everything
from this point
onwards
...

I tried using sed '/<!--START OF FILE -->/,/x x x x x x x/d' test.txt but this removes the block between the first occurence of x x x x x x x which is not what I want.

Best Answer

This is quite the opposite of

How to print lines between pattern1 and 2nd match of pattern2?

With sed you'd do something like:

sed -n '/PATTERN1/,$!{         # if not in this range
p;d                            # print and delete
}
/PATTERN2/!d                   # delete if it doesn't match PATTERN2
x;//!d                         # exchange and then, again, delete if no match
: do                           # label "do" (executed only after the 2nd match)
n;p                            # get the next line and print
b do' infile                   # go to label "do"

or, in one line (on gnu setups):

sed -n '/PATTERN1/,$!{p;d;};/PATTERN2/!d;x;//!d;: do;n;p;b do' infile

Sure, it's easier with awk and counters. I'll leave that as an exercise for you...

Related Question