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:
/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.
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