Use the -m flag to set the max number of lines found for a matching pattern.
Let’s return to our numbers.txt file and duplicate the content so that we have 5 lines:
123456789
123456789
123456789
123456789
123456789If we wanted to search for the pattern 345, we would run:
$ grep "345" numbers.txt
123456789
123456789
123456789
123456789
123456789As expected, the grep command will return every line with 345 in it.
Add the -m flag to limit it to the max number you define:
grep -m 3 "345" numbers.txt
123456789
123456789
123456789