Remove line containing certain string and the following line

  • I use this

    cat foo.txt | sed '/bar/d'

    to remove lines containing the string bar in the file.

    I would like however to remove those lines and the line directly after it. Preferably in sed, awk or other tool that's available in MinGW32.

    It's a kind of reverse of what I can get in grep with -A and -B to print matching lines as well as lines before/after the matched line.

    Is there any easy way to achieve it?

    Just for information: I'm analyzing logs in which entries are two-liners. So I want to find an entry matching the pattern and remove it as well as the next line. Hence I don't need to handle consecutive match lines, but thanks anyway for the completeness of your answers!

  • If you have GNU sed (so non-embedded Linux or Cygwin):

    sed '/bar/,+1 d'

    If you have bar on two consecutive lines, this will delete the second line without analyzing it. For example, if you have a 3-line file bar/bar/foo, the foo line will stay.

    +1 for the length :) In my particular example I don't have consecutive `bar`s so this one is super easy to remember.

    `sed '/bar/d'` if you just want to "Remove line containing certain string" and **not** the next.

    If I want to remove all the lines after math then?

    @Pandya That's different. You can use e.g. `sed '/math/q'`

    @Gilles Thanks that worked, but I might have done some mistake and asked the question.

    To break down the command: the first part `/bar/,+1/` is a sed address ( that says start at the regexp `/bar/`, then a `,` as a separator between start/end addresses, and end `+1` lines (from the start). Then the `d` is the command (delete)

    I actually wanted to delete the matching line so I just replaced +1 with +0 and it worked! like: sed '/bar/,+0 d'

    @A.K. If you just want to delete the matching line, it's even simpler: `sed '/bar/d'`

License under CC-BY-SA with attribution

Content dated before 6/26/2020 9:53 AM