Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete the line that matches a pattern and the line after it with sed?

Tags:

linux

unix

sed

I have a file that looks something like:

good text
good text
FLAG bad text
bad text
good text
good text
good test
bad Text FLAG bad text
bad text
good text

I need to delete any line containing "FLAG" and I always need to delete the one line immediately following the "FLAG" line too.

"FLAG" lines come irregularly enough that I can't rely on any sort of line number strategy.

Anyone know how to do this with sed?

like image 238
bob.sacamento Avatar asked Jul 26 '13 21:07

bob.sacamento


People also ask

How do you delete a line with a pattern in Linux?

If you want to delete Nth line only if it contains a pattern, then in place of $ place the line number. Note: In all the above examples, the sed command prints the contents of the file on the unix or linux terminal by removing the lines.

How do you delete a line in a file using sed?

To delete a line, we'll use the sed “d” command. Note that you have to declare which line to delete. Otherwise, sed will delete all the lines.

How do you insert a sed line after a pattern?

The sed command can add a new line after a pattern match is found. The "a" command to sed tells it to add a new line after a match is found. The sed command can add a new line before a pattern match is found. The "i" command to sed tells it to add a new line before a match is found.

How do I remove a specific pattern from a Unix file?

N command reads the next line in the pattern space. d deletes the entire pattern space which contains the current and the next line. Using the substitution command s, we delete from the newline character till the end, which effective deletes the next line after the line containing the pattern Unix.


1 Answers

Using an extension of the GNU version of sed:

sed -e '/FLAG/,+1 d' infile

It yields:

good text
good text
good text
good text
good test
good text
like image 129
Birei Avatar answered Oct 08 '22 00:10

Birei