[grep] Grep only the first match and stop

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

returns:

Pulsanti Operietur
Pulsanti Operietur

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

This question is related to grep

The answer is


-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.

You can use head -1 to solve this problem:

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

explanation of each grep option:

-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

My grep-a-like program ack has a -1 option that stops at the first match found anywhere. It supports the -m 1 that @mvp refers to as well. I put it in there because if I'm searching a big tree of source code to find something that I know exists in only one file, it's unnecessary to find it and have to hit Ctrl-C.


A single liner, using find:

find -type f -exec grep -lm1 "PATTERN" {} \; -a -quit

You can use below command if you want to print entire line and file name if the occurrence of particular word in current directory you are searching.

grep -m 1 -r "Not caching" * | head -1

You can pipe grep result to head in conjunction with stdbuf.

Note, that in order to ensure stopping after Nth match, you need to using stdbuf to make sure grep don't buffer its output:

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

As soon as head consumes 1 line, it terminated and grep will receive SIGPIPE because it still output something to pipe while head was gone.

This assumed that no file names contain newline.