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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With