How do I limit the number of results returned from grep?
Solution 1:
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!
Solution 2:
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.
Solution 3:
Awk approach:
awk '/pattern/{print; count++; if (count==10) exit}' file
Solution 4:
For 2 use cases:
- I only want n overall results, not n results per file, the
grep -m 2
is per file max occurrence. - 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