【问题标题】:How can I make grep stop after hitting a first pattern match in a large file?在大文件中遇到第一个模式匹配后,如何让 grep 停止?
【发布时间】:2014-03-19 17:59:31
【问题描述】:

我有很多这样的行:

a|b|c
e|f|2
h|i|j

我想在第 3 列中找到仅包含数字的第一行(这将是示例中的第 2 列)。我怎样才能在不转储所有数据并将其导入头部的情况下 grep 呢?

【问题讨论】:

    标签: shell grep


    【解决方案1】:

    您可以在 grep 中使用-m1 选项:

    grep -m1 "[0-9]$" file
    

    根据man grep:

     -m num, --max-count=num
             Stop reading the file after num matches.
    

    或者更准确地说,使用 awk:

    awk -F'|' '$3 ~ /^[0-9]+$/{print; exit}' file
    e|f|2
    

    【讨论】:

    • 请注意,-m 是 GNUism。
    【解决方案2】:

    POSIX 解决方案是使用sed 并在第一次匹配后退出:

    sed -n '/|[0-9]*$/{p;q;}' file    # print and quit
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-17
      • 1970-01-01
      • 2018-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-15
      相关资源
      最近更新 更多