我使用grep递归地搜索目录,并使用以下参数,希望只返回第一个匹配项。不幸的是,它返回的不止一个--实际上是我上次查看时返回的两个。我似乎有太多的争论,特别是没有得到想要的结果。:-/
# grep -o -a -m 1 -h -r "Pulsanti Operietur" /path/to/directory
返回:
Pulsanti Operietur
Pulsanti Operietur
也许grep不是最好的方法?你告诉我,非常感谢。
发布于 2012-12-31 02:44:04
-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
发布于 2012-12-31 02:50:27
我的类似grep-a的程序ack
有一个-1
选项,它在任何地方找到第一个匹配项时停止。它也支持@mvp所指的-m 1
。我之所以把它放在那里,是因为如果我要搜索一棵巨大的源代码树来查找我知道只存在于一个文件中的内容,那么就没有必要找到它并按Ctrl-C组合键。
发布于 2020-01-30 13:02:34
你可以使用下面的命令,如果你想要打印整个行和文件名,如果你正在搜索的当前目录中出现特定的单词。
grep -m 1 -r "Not caching" * | head -1
https://stackoverflow.com/questions/14093452
复制相似问题