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.
(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.
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.
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:
grep -m 2
is per file max occurrence. 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With