如何使用 sed 删除匹配的行、上面的行和下面的行? [英] How do I delete a matching line, the line above and the one below it, using sed?

查看:197
本文介绍了如何使用 sed 删除匹配的行、上面的行和下面的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个文件中多次出现以下序列:

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

yyyy
xxxx
zzzz

我有一个匹配 xxxx 的正则表达式.每当有匹配项时,我想删除该行、之前的行(例如 yyyy)和之后的行(例如 zzzz).我如何使用 sed 来做到这一点?

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?

推荐答案

诀窍是存储在保持空间"中看到的最后一行.

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>

x 开始 - 将当前输入行与保留空间 (x) 交换,然后第一行不打印任何内容 (1d),后续行打印刚刚从保持空间交换的行 (p),在最后一行再次交换保持空间并打印其中的内容 ($x{xp}.这就留下了当我们到达目标行时要做的事情(从 /^xxxx/ 开始) - 将接下来的两行读入模式空间(nn>) 并将模式空间与保留空间 (x) 交换 - 这将保留空间与我们要打印的下一行以及模式空间与匹配之前的行,我们不这样做想要,所以我们放弃它 (d)

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)

这篇关于如何使用 sed 删除匹配的行、上面的行和下面的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆