Answers:
-m 1表示返回任何给定文件中的第一个匹配项。但是它仍然会继续在其他文件中搜索。另外,如果同一行中有两个或多个匹配项,则将全部显示。
head -1用来解决此问题:grep -o -a -m 1 -h -r "Pulsanti Operietur" /path/to/dir | head -1
-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
-r显然除外),但是它们不应受到伤害(-a尽管我不会使用)
grep -m 1返回了两个实例。|head -1解决了!
first not first from result。此答案将在任何文件中打印第一个匹配项并停止。您还期望什么?
您可以将grep结果head与stdbuf结合使用。
注意,为了确保在第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在消失时仍会输出一些内容给管道。
假定没有文件名包含换行符。
xargs:find . -name '*.gz' | xargs -I '{}' stdbuf -oL zgrep -al 'pattern' {} | head -n 1。但是,这不会在第一个比赛中终止。有什么建议吗?
grep的--line-buffered选项防止开销缓冲,而无需调用额外的效用?
我的类似grep的程序ack有一个-1选项,该选项会在任何地方的第一个匹配项处停止。它也支持-m 1@mvp所引用的。我把它放在那里是因为如果我正在搜索一棵大的源代码树以找到仅存在于一个文件中的已知内容,则无需找到它并且必须按Ctrl-C。
ag可能很快,但是它没有-1在这种情况下有用的选项
如果要在搜索的当前目录中出现特定单词,则要打印整行和文件名,可以使用以下命令。
grep -m 1 -r "Not caching" * | head -1
单个衬板,使用find:
find -type f -exec grep -lm1 "PATTERN" {} \; -a -quit
grep -r工作速度更快-它只有一个副本可以进行目录遍历。