Stop grep After the First Match with the -m 1 Option
Stop grep after the first match with -m 1, which also ends a pipeline early. After the last match, GNU grep still prints any trailing context lines you asked for.
You only need the first line that matches, and reading the whole file or pipeline would waste time.
seq 1 1000000 > nums.txt
grep -m 1 -n 7 nums.txt
yes | grep -m 1 y
printf 'x\nx\nx\n' | grep -m 2 -c x
printf 'err\nctx1\nctx2\nerr\nctx3\n' | grep -m 1 -A 2 err7:7
y
2
err
ctx1
ctx2-m NUM stops reading after NUM selected lines. On a file of a million lines the match for 7 came back at once, with -n giving its line number. In the pipe case, yes | grep -m 1 y finished because yes received a broken pipe when grep exited. With -c, the count is capped by -m, so two of three matching lines print 2, and trailing context from -A is still printed after the last match. See General Output Control in the manual.
-m counts lines and not matches inside a line, and with -v it counts the lines that do not match. When the input comes from a slow command, grep stops at once, but the producer may notice only on its next write.