我正在使用grep和以下参数递归地搜索一个目录,希望只返回第一个匹配。不幸的是,它返回了不止一个——上次我查看时,实际上是两个。我似乎有太多的争论,尤其是没有得到预期的结果。: - /
# grep -o -a -m 1 -h -r "Pulsanti Operietur" /path/to/directory
返回:
Pulsanti Operietur
Pulsanti Operietur
也许grep不是最好的方法?你来告诉我,非常感谢。
我正在使用grep和以下参数递归地搜索一个目录,希望只返回第一个匹配。不幸的是,它返回了不止一个——上次我查看时,实际上是两个。我似乎有太多的争论,尤其是没有得到预期的结果。: - /
# grep -o -a -m 1 -h -r "Pulsanti Operietur" /path/to/directory
返回:
Pulsanti Operietur
Pulsanti Operietur
也许grep不是最好的方法?你来告诉我,非常感谢。
-m 1表示返回任何给定文件中的第一个匹配项。但它仍将继续在其他文件中搜索。此外,如果在同一行中有两个或多个匹配,则将全部显示。
你可以用head -1来解决这个问题:
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-a的程序ack有一个-1选项,在任何地方找到的第一个匹配处停止。它也支持@mvp所指的- m1。我之所以把它放在那里,是因为如果我正在搜索一棵巨大的源代码树,以找到我知道只存在于一个文件中的某些东西,那么就没有必要找到它并必须按Ctrl-C。
您可以将grep结果与stdbuf一起管道到head。
注意,为了确保在第n次匹配后停止,你需要使用stdbuf来确保grep不缓冲它的输出:
stdbuf -oL grep -rl 'pattern' * | head -n1
stdbuf -oL grep -o -a -m 1 -h -r "Pulsanti Operietur" /path/to/dir | head -n1
stdbuf -oL grep -nH -m 1 -R "django.conf.urls.defaults" * | head -n1
只要head消耗了1行,它就被终止,grep将接收SIGPIPE,因为当head消失时,它仍然向pipe输出一些东西。
这假设没有文件名包含换行符。
你可以使用下面的命令,如果你想打印整个行和文件名,如果特定的字出现在当前目录你正在搜索。
grep -m 1 -r "Not caching" * | head -1
阅读grep手册(man grep),这是查找第一个与扩展regexp匹配的最小命令。示例获取以太网名称,在我的笔记本电脑不是eth0 !
$ ifconfig | grep -E -o -m 1 "^[a-z0-9]+"
解释: -E用于扩展regexp, -o只返回匹配项本身, -m 1,只查找一个匹配项