399
votes

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.

6

6 Answers

623
votes

-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
39
votes

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.

24
votes

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.

12
votes

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
3
votes

Reading the grep manual (man grep) this is the minimum command to find first match with Extended regexp. Example getting the ethernet name that in my laptop is NOT eth0 !

$ ifconfing | grep -E -o -m 1 "^[a-z0-9]+"

Explanation: -E for extended regexp, -o to return only the match, -m 1 to look only one line

1
votes

A single liner, using find:

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