How do I limit the number of results returned from grep?

Jas picture Jas · Feb 16, 2011 · Viewed 154.8k times · Source

I would like to say 10 lines max from grep.

I don't want my computer to work hard. I want it to stop after 10 results found by grep. Is it possible?

Answer

Erik Pilz picture Erik Pilz · Feb 16, 2011

The -m option is probably what you're looking for:

grep -m 10 PATTERN [FILE]

From man grep:

-m NUM, --max-count=NUM
        Stop reading a file after NUM matching lines.  If the  input  is
        standard  input  from a regular file, and NUM matching lines are
        output, grep ensures that the standard input  is  positioned  to
        just  after the last matching line before exiting, regardless of
        the presence of trailing context lines.  This enables a  calling
        process  to resume a search.

Note: grep stops reading the file once the specified number of matches have been found!