Skip to content
shellhacks.dev
Text Processing

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.

1 min read
Summarize in AI

You only need the first line that matches, and reading the whole file or pipeline would waste time.

Shell
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 err
Text
7: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.

Taggedgreptext
Share

More snippets

Text Processing

Replace Only the Nth Match on a Line with sed

Replace only the second or a later match on a line with a numeric flag on the s command, and add g to replace from that match onward. The count restarts on every line.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.