2

I use below 'sed' command to delete 'N' no of lines after every match of a pattern in a file.

sed -i '/test/,+1d' file.txt

Suppose, I have a pattern 'test' in a file called file.txt. And I want to delete 2 lines only after the second occurrence of a word 'test'. Is there any sed/awk one liner for this?

Example: file.txt

test
apple
mango
test
brinjal
carrot
test
banana
gauva
3

To delete the second test and the line that follows it:

$ awk '/test/ && ++f == 2 {getline;next} 1' file.txt
test
apple
mango
carrot
test
banana
gauva

How it works:

  1. /test/ && ++f == 2 {getline;next}

    Every time we meet line matching the regex test, we increment variable f and, if f==2, we read in another line with getline and then jump to start over on the next line. This has the effect of discarding both the test line and the following line.

  2. 1

    For all other lines, we print the line. (1 is awk shorthand for print-the-line.)

Alternate

In this approach, we capture the line number of the second occurrence of the line matching test in the variable N.

We print a line only if N is not yet assigned or else if the current line is at least 2 lines after line number N.

$ awk '/test/ && ++f == 2 {N=NR} (!N) || NR>=N+2' file.txt
test
apple
mango
carrot
test
banana
gauva

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.