如何限制从 grep 返回的结果数?

新手上路,请多包涵

我想说 grep 最多 10 行。

我不想让我的电脑努力工作。我希望它在 grep 找到 10 个结果后停止。可能吗?

原文由 Jas 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.8k
2 个回答

-m 选项可能是您正在寻找的:

 grep -m 10 PATTERN [FILE]

man grep

 -m NUM, --max-count=NUM
        Stop reading a file after NUM matching lines.  If the  input  is
        standard  input  from a regular file, and NUM matching lines are
        output, grep ensures that the standard input  is  positioned  to
        just  after the last matching line before exiting, regardless of
        the presence of trailing context lines.  This enables a  calling
        process  to resume a search.

注意:一旦找到指定数量的匹配项,grep 就会停止读取文件!

原文由 Erik Pilz 发布,翻译遵循 CC BY-SA 4.0 许可协议

另一种选择是只使用 head

 grep ...parameters... yourfile | head

这不需要搜索整个文件 - 当找到前十个匹配行时它将停止。这种方法的另一个优点是即使您使用带有 -o 选项的 grep 也将返回不超过 10 行。

例如,如果文件包含以下行:

 112233
223344
123123

然后这是输出的差异:

$ grep -o '1.'您的文件 |头-n2
11
12

$ grep -m2 -o '1.'
11
12
12

使用 head 根据需要只返回 2 个结果,而 -m2 返回 3。

原文由 Mark Byers 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题