Grep 仅第一场比赛并停止 [英] Grep only the first match and stop

查看:14
本文介绍了Grep 仅第一场比赛并停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有以下参数的 grep 递归搜索目录,希望只返回第一个匹配项.不幸的是,它返回了不止一个——实际上是我上次查看时返回的两个.似乎我有太多的论点,尤其是没有得到想要的结果.:-/

I'm searching a directory recursively using grep with the following arguments hoping to only return the first match. Unfortunately, it returns more than one -- in-fact two the last time I looked. It seems like I have too many arguments, especially without getting the desired outcome. :-/

# grep -o -a -m 1 -h -r "Pulsanti Operietur" /path/to/directory

返回:

Pulsanti Operietur
Pulsanti Operietur

也许 grep 不是最好的方法?你告诉我,非常感谢.

Maybe grep isn't the best way to do this? You tell me, thanks very much.

推荐答案

-m 1 表示返回任何给定文件中的第一个匹配项.但它仍会继续在其他文件中搜索.此外,如果同一行中有两个或更多匹配,则将全部显示.

-m 1 means return the first match in any given file. But it will still continue to search in other files. Also, if there are two or more matched in the same line, all of them will be displayed.

grep -o -a -m 1 -h -r "Pulsanti Operietur" /path/to/dir | head -1

每个grep选项的解释:

-o, --only-matching, print only the matched part of the line (instead of the entire line)
-a, --text, process a binary file as if it were text
-m 1, --max-count, stop reading a file after 1 matching line
-h, --no-filename, suppress the prefixing of file names on output
-r, --recursive, read all files under a directory recursively

这篇关于Grep 仅第一场比赛并停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆