小智 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就会停止读取文件!
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.
Awk方法:
awk '/pattern/{print; count++; if (count==10) exit}' file
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
130725 次 |
| 最近记录: |