检测与 sed 模式匹配的连续两行 [英] detect two consecutive lines matching a pattern with sed
问题描述
我正在寻找与某个模式匹配的连续两行,比如使用 sed 包含单词 'pat' 并且注意到我有时可以使用以下命令检测到它:
I am looking for two consecutive lines matching a certain pattern, say containing word 'pat' using sed and have noticed that I am able to detect it sometimes with this command:
sed -n 'N; /.*pat.*\n.*pat.*/p'
但是如果重复的行号不是相同的奇偶校验,这个命令就会失败,我认为这是因为我们正在搜索第 1+2、3+4、5+6 行等等.如果是这种情况,这样做的正确方法是什么?
but this command fails if the line numbers for the duplicates are not of the same parity and I assume it's because we're searching lines 1+2, 3+4, 5+6 etc.. if this is the case, what would be the correct way to do this?
推荐答案
为什么需要sed
?我可以推荐 awk
吗?
Why does it need to be sed
? May I suggest awk
?
awk '{/pat/?f++:f=0} f==2' file
如果找到pat
,用1
增加f
如果未找到pat
,则将f
重置为0
如果 f==2
打印该行.
If pat
is found, increment f
with 1
If pat
is not found, reset f
to 0
If f==2
print the line.
这篇关于检测与 sed 模式匹配的连续两行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!