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

Jas*_*Jas 156 unix linux bash sh

我想说grep最多10行.

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

小智 214

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

grep -m 10 PATTERN [FILE]
Run Code Online (Sandbox Code Playgroud)

来自-m,

-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.
Run Code Online (Sandbox Code Playgroud)

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

  • @Jason:这似乎不是这样的:grep在我的笔记本电脑上使用`-m 1`和1.579s而不使用1000万行的文件需要0.005s. (6认同)
  • 管道进入`tail`通常会起作用,但特别是如果你正在使用上下文,例如`grep -A10 PATTERN`,使用​​`tail`截断上下文,而不是结果的数量.这个答案就是我想要的. (3认同)
  • 嗨,它试过了,它基本上可以用,但是grep在发现前10行后似乎并没有停止思考,就像他继续思考并“使用我的cpu”一样,只是不printint,这是正确的吗?坦斯克 (2认同)
  • `-m` 与旧版本 grep 中的 `-A/-B/-C` 选项冲突,例如可以在 Ubuntu 16.04 上找到的 `2.25`,只输出 `m` 行而不是由 `-A 定义的行/-B/-C`。较新的版本没有这个问题(在 Arch 上用 `3.1` 测试)。 (2认同)

Mar*_*ers 64

另一个选择就是使用head:

grep ...parameters... yourfile | head
Run Code Online (Sandbox Code Playgroud)

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

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

112233
223344
123123
Run Code Online (Sandbox Code Playgroud)

那么这就是输出的差异:

$ grep -o '1.' yourfile | head -n2
11
12

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

使用head时只返回2个结果,而-m2返回3.

  • 使用head实际上并不会阻止grep在整个文件中运行.在grep中使用-m选项可以. (16认同)
  • 请注意,您不能使用`| 将`grep`与`-A`或`-B`一起使用时的head`管道(因此不仅要搜索结果(`-o`),还要搜索上下文).在这种情况下,你留下`-m`来告诉grep要返回结果的行数. (3认同)

kur*_*umi 7

Awk方法:

awk '/pattern/{print; count++; if (count==10) exit}' file
Run Code Online (Sandbox Code Playgroud)