Stop grep after Nth files matched

grep

I have many files I need to search for some string. I'm using grep -rl 'pattern' * to find files that contain the pattern. However, I'm only interested in file count – if string occurs in more than N files, I want grep to stop immediately after hitting Nth match(as searching through the whole file hierarchy is long operation). It would be nice if it returned some meaningful exit code, but if that's impossible then I can just pipe it to wc without a problem.

How can I tell grep to stop searching other files after matching Nth file?

Best Answer

You can pipe grep result to head.

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

As soon as head consumed 10 lines, 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.

Related Question