Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

bash

unix

sh

People also ask

Does grep have a limit?

Though grep expects to do the matching on text, it has no limits on input line length other than available memory, and it can match arbitrary characters within a line.

How do you give a grep range?

(1[0-9]|20)" . Your regular expression in grep asks for 1 or 2, and 2 or 0. 1[0-9] will match anything between 10 to 19 as well as 20.

How do I stop grep after first match?

The grep command has an -m or --max-count parameter, which can solve this problem, but it might not work like you'd expect. This parameter will make grep stop matching after finding N matching lines, which works great as it will limit the output to one line, always containing the first match.

Does grep have a return value?

grep will return zero only when some string is matched. this rule is applicable for grep -c as well.


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!


Another option is just using head:

grep ...parameters... yourfile | head

This won't require searching the entire file - it will stop when the first ten matching lines are found. Another advantage with this approach is that will return no more than 10 lines even if you are using grep with the -o option.

For example if the file contains the following lines:

112233
223344
123123

Then this is the difference in the output:

$ grep -o '1.' yourfile | head -n2
11
12

$ grep -m2 -o '1.'
11
12
12

Using head returns only 2 results as desired, whereas -m2 returns 3.


Awk approach:

awk '/pattern/{print; count++; if (count==10) exit}' file

For 2 use cases:

  1. I only want n overall results, not n results per file, the grep -m 2 is per file max occurrence.
  2. I often use git grep which doesn't take -m

A good alternative in these scenarios is grep | sed 2q to grep first 2 occurrences across all files. sed documentation: https://www.gnu.org/software/sed/manual/sed.html