【问题标题】:Print the last 1,2,3..Nth or first 1,2,3...Nth matching block pattern using awk or sed使用 awk 或 sed 打印最后 1,2,3..Nth 或第 1,2,3...Nth 匹配块模式
【发布时间】:2020-06-13 15:12:04
【问题描述】:

模式1
一个
b
图案2
光盘
图案1
重新
图案2
gh
图案1
ef
图案2
qw e

我可以显示所有匹配的模式

sed -n '/pattern1/,/pattern2/p'

选择第二个匹配模式或任意Nth by

awk -vM=2 '(x+=/pattern1/)==M&&x+=/pattern2/' file 

模式1
重新
模式2

只打印最后一个匹配的模式

awk 'x+=/pattern1|pattern2/{!y++&&B="";B=B?B"\n"$0:$0;x==2&&y=x=0}END{print B}' file   

模式1
ef
模式2

但是如何打印例如最后/前 2 个或第 N 个匹配块模式?
图案1
重新
图案2
图案1
ef
模式2

【问题讨论】:

  • 编辑您的问题以显示您尝试了什么。然后我们可以帮助你。祝你好运。

标签: bash awk sed


【解决方案1】:

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

sed -n '/pattern1/,/pattern2/{p;/pattern2/{H;x;s///2;x;T;q}}' file

这会打印 pattern1pattern2 的前 2 个匹配项,然后退出。

sed -nr '/pattern1/,/pattern2/H;$!b;x;s/.*((pattern1.*){2})$/\1/p' file

这将打印 pattern1pattern2 的最后 2 个匹配项。

【讨论】:

    猜你喜欢
    • 2013-07-28
    • 2011-07-20
    • 2016-08-15
    • 2020-08-16
    • 2016-07-01
    • 1970-01-01
    • 2010-12-16
    • 1970-01-01
    相关资源
    最近更新 更多