Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "sed" to delete a line containing something and the next line

Tags:

regex

sed

Assume a file with the following contents:

good
good bad
next of baaaad
good

I want to use sed to delete lines which contain "bad" and the next line of these lines. In above example I want to delete line 2 and line 3.

How can I do that?

I tried this, but it doesn't work:

ebra@him:/tmp$ cat iio | sed -e "s/\n.*bad.*\n.*//"
good
good bad
next of baaaad
good
like image 528
Ebrahim Ghasemi Avatar asked Dec 18 '25 10:12

Ebrahim Ghasemi


1 Answers

With GNU sed, you can specify address ranges with matches and a number of lines following the match:

$ sed '/bad/,+1d' infile
good
good
like image 148
Benjamin W. Avatar answered Dec 20 '25 06:12

Benjamin W.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!