【问题标题】:Grep Next Line Only If Two Lines Above Match String Consecutively仅当上面的两行连续匹配字符串时才 Grep 下一行
【发布时间】:2017-01-28 18:39:44
【问题描述】:

我正在使用以下命令来匹配文件中的以下行:

cat file.txt | grep -A 1 'match' > output.txt

这使我可以在以下文件中找到“匹配”后获取该行:

match
random text line 1
match
match
match
random text line 2
match
random text line 3
match
match
random text line 4
match
random text line 5
match
random text line 6
match
random text line 7
match
random text line 8
match
match
random text line 9

但是,我只需要返回 2 个或更多连续“匹配”行之后的行。在这种情况下,输出将是:

random text line 2
random text line 4
random text line 9

我尝试过使用grep -A 2 'match' | grep -A 1 'match' 的组合,但它不起作用,因为它是多余的。只有当有两行连续的行时,我才坚持如何匹配。如果它更有效,我也愿意使用 awk 或 sed 进行匹配。任何方向将不胜感激。

【问题讨论】:

    标签: linux bash awk sed grep


    【解决方案1】:

    grep 代表g/re/p,即它用于全局查找正则表达式并打印结果,仅此而已。这不是您尝试这样做的全部,因此 grep 将是尝试使用的错误工具。对于通用文本操作,使用的标准工具是 awk:

    $ awk '/match/{c++;next} c>1; {c=0}' file
    random text line 2
    random text line 4
    random text line 9
    

    【讨论】:

    • 也感谢您的解释。这很好用。我真的需要更多地使用awk。看起来很酷(而且准确)的事情要做:-)
    • 实际上,当行的顺序变为match, random text line 11, match, random text line 12, match, random text line 13 时,它会返回一个不正确的“随机文本行”。在这种情况下,将输出第 13 行(即使它上面只有一个“匹配”而不是两个)。我可以编辑您的答案并提供失败的示例吗?
    • 这是复制它的一种方式。但是,我得到的行只有 1 个“匹配”,而不是 2 个连续的“匹配”行:-/
    • 啊,完美!非常非常感谢埃德。我非常感谢您的知识和技能。
    • 不客气。我已经删除了我的 cmets 来整理 Q/A。
    猜你喜欢
    • 2011-05-28
    • 1970-01-01
    • 1970-01-01
    • 2017-08-09
    • 2022-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多