Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
576 views
in Technique[技术] by (71.8m points)

regex - How do I delete a matching line, the line above and the one below it, using sed?

I have the following sequence occurring multiple times in a file:

yyyy
xxxx
zzzz

I have a regex that matches xxxx. Whenever there is a match, I want to delete that line, the line before (e.g. yyyy) and the line after it (e.g. zzzz). How can I use sed to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The trick is to store the last line seen in the "hold space".

sed -n '
/^xxxx/{n
        n
        x
        d
       }
x
1d
p
${x
  p
 }
' <input file>

Starting with the x - swap the current input line with the hold space (x), then for the first line don't print anything (1d), subsequent lines print the line just swapped from the hold space (p), on the last line swap the hold space again and print what was in it ($x{x p}. That leaves what to do when we hit the target line (starting /^xxxx/) - read the next two lines into the pattern space (n n) and swap the pattern space with the hold space (x) - this leaves the hold space with next line we want to print and the pattern space with the line before the match, which we don't want, so we ditch it (d)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...