如何使用 sed 删除模式第二个匹配之前的所有行?

问题描述 投票:0回答:4

我有以下文件:

first
second
third
fourth
third
fifth
sixth

使用

cat file | sed -n '/third/,$p'
我可以从第一场比赛开始打印,以获得:

third
fourth
third
fifth
sixth

是否可以修改

sed
命令,使其基本上忽略第一个匹配并从第二个匹配中打印?那将是:

third
fifth
sixth
bash unix sed
4个回答
2
投票

使用 sed:

sed '1,/third/d' file | sed -n '/third/,$p'

输出:

第三
第五
第六

2
投票

这里有一个

awk
,它通过保留一个缓冲区来存储行中出现
third
的所有行,并在再次找到
third
时重置缓冲区来实现此目的:

awk '/third/{p=$0 RS; next} p{p=p $0 RS} END{printf "%s", p}' file

third
fifth
sixth

或者,您也可以使用这个

tac + awk

tac file | awk '1; /third/{exit}' | tac

third
fifth
sixth

0
投票

使用 gnu sed

sed '/third/!d;:A;N;/\nthird/!{s/[^\n]*\n//;bA };s/[^\n]*\n//;:B;N;bB' infile

0
投票

这可能对你有用(GNU sed):

sed -E '/third/{x;s/^/x/;/x{2}/{x;:a;n;ba};x};d' file

在保留空间中设置一个计数器,并测试每次出现

third
是否有两次或两次以上。

如果是这样,只需打印文件的其余部分。

否则,删除当前行。

© www.soinside.com 2019 - 2024. All rights reserved.