How to delete the 3rd occurrence of a pattern in a file, and beyond

1

0

How can I find the third occurrence of a pattern in a file (Note: not in a line) and delete the line containing the pattern and n lines below that (say, 5 lines below).

e.g.,

COVER
fafjasfj
isfapifj
ajfsdaijf
COVER
oaijfeiahf
aasdf
fafadf
df
This is a COVER                                             *
efjafa                                                      *
aifaidfj                                                    *
aifhaidfh                                                   *
idfhaifh                                                    *
aidfhiadhf                                                  *
aifhaifh
iafaishf
jgsjg
fbsfgbf

I want to delete the complete line containing the third occurrence of the pattern COVER and the five lines below that. These lines are indicated with *s. (Note: the *s are not part of the file.

Mukesh Babu

Posted 2014-12-07T16:39:59.820

Reputation: 11

It isn't clear exactly what you're asking. Are you looking for the 3rd occurrence of any text or text that you specify somewhere? Is it always 5 lines or is that a variable? – fixer1234 – 2014-12-07T17:18:14.880

I would like to delete the 3rd occurrence of a particular text and few lines below that , that 5 is a variable as – Mukesh Babu – 2014-12-08T10:40:21.220

Answers

1

$ awk '$1=="COVER"{l++}l==3{l2++} l!=3 || l2>6' file
COVER
fafjasfj
isfapifj
ajfsdaijf
COVER
oaijfeiahf
aasdf
fafadf
df
aifhaifh
iafaishf
jgsjg
fbsfgbf

The last {print} statement is not necessary because by default, awk print current line on a true condition.

Gilles Quenot

Posted 2014-12-07T16:39:59.820

Reputation: 3 111