简体   繁体   中英

How to delete the line that matches a pattern and the line after it with 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?

Using an extension of the GNU version of :

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

It yields:

good text
good text
good text
good text
good test
good text

This works, and doesn't depend on any extensions:

sed '/FLAG/{N
d
}' infile

N reads the next line into the pattern space, then d deletes the pattern space.

Here is one way with awk :

awk '/FLAG/{f=1;next}f{f=0;next}1' file

or

awk '/FLAG/{getline;next}1' file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM