Linux 如何在匹配/匹配后使用“sed”删除 2 行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8323287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 02:38:30  来源:igfitidea点击:

How can I use "sed" to delete 2 lines after match/matches?

linuxshellsed

提问by wael

I have the following command : sed -i -e '/match1/,+2d' filex, which deletes 2 lines after finding the match "match1" in the file "file x". I want to add several matches to it, like match1, match 2 ....

我有以下命令 : sed -i -e '/match1/,+2d' filex,它在文件“文件 x”中找到匹配项“match1”后删除 2 行。我想向它添加几个匹配项,例如 match1、match 2 ....

So it will delete 2 lines after finding any of the matches, how can I achieve this ?

因此,它会在找到任何匹配项后删除 2 行,我该如何实现?

回答by ziu

Two ways, depending upon the sed version and platform:

两种方式,取决于 sed 版本和平台:

sed -e '/match1/,+2d' -e '/match2/,+2d' < oldfile > newfile

or

或者

sed -e '/match1\|match2/,+2d' < oldfile > newfile

回答by Max

Not a sed user but it seems to me you could use :

不是 sed 用户,但在我看来您可以使用:

sed -i -e '/(match1|match2)/,+2d' filex

Otherwise you could, if that's possible for you to do, do :

否则,如果您可以这样做,您可以这样做:

sed -i -e '/match1/,+2d' filex && sed -i -e '/match2/,+2d' filex

EDIT: Looks like I had the right idea but ziu got it.

编辑:看起来我的想法是正确的,但 ziu 明白了。

回答by sehe

If I understand you correctly, you want

如果我理解正确,你想要

sed -e '/match1/,+2d' input.txt

For example, create input with seq 10 | sed '3i match1' > input.txt:

例如,使用以下命令创建输入seq 10 | sed '3i match1' > input.txt

1
2
match1
3
4
5
6
7
8
9
10

The output of sed -e '/match1/,+2d' input.txtwould be:

的输出sed -e '/match1/,+2d' input.txt将是:

1
2
5
6
7
8
9
10