[grep] Stop after a specified number of matching lines

Created on November 30, 2026

Pass -m to limit how many matching lines grep prints. Here ^a selects lines starting with a, and -m 2 stops after two matches.

printf '%s\n' apple banana apricot avocado | grep -m 2 '^a'
apple
apricot

For file input, the limit applies separately to each file. In GNU grep, you can also write --max-count=2.

Reference

Shell command grep