How to find first match in multiple files

command linefindgrep

Is there a way for the find command to search for the first match or occurrence of a string or pattern within each of multiple files? I've been using the usual syntax:

 find dir -iname '*.ext' -exec command 'pattern' {} \;

(I also happen to be searching pdfs with -exec pdfgrep but suppose that would be a special case of the general problem and may be dealt with afterwards or separately.)

Keep in mind this is not same as the commonly-asked problem of producing the first result from a search using find with -quit or head -n 1.

Best Answer

Just use the -m option of GNU grep which stops reading the file after (in the example) one match.

find dir -iname '*.ext' -exec grep -m 1  'pattern' {} \;
Related Question