grep is a search utility in Linux used for matching content. By default, it will print out any line that matches, which might include a lot of output. If you only care about the first match, you can limit the output to just the first line.
Limiting Output with grep -m
grep command has an
--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. We can verify this with the
-n flag to print the line numbers.
grep -m 1 "foo" file
However, this has some downsides you should be aware of. It doesn’t stop after N matches, it stops after N lines. This will cause
grep to match multiple times on each line, which can be a problem when used with the
-o flag, which prints each match on a new line.
Also, it’s only N lines per file, so when used against multiple files it will print out the first matching line for each file.
Using head To Limit grep Output
The alternative is to pipe the output to a different command,
head, which will simply cut off the input after N lines. It’s still a little useful to use
-m 1 with
grep though, as it will stop processing large files if a match is found early.
grep "foo" file_one.txt | head -1
This works with the
-o flag to print only the first match, even if there are multiple matches in a file:
However, be careful when using this with multiple files. Using
head will print the first matched line in any file. This can be a problem as
grep prints output in the order it processes the files, and you may not know the order the files will be processed in unless you sort them manually before passing them to
Similarly, you can also use
tail to print the last matching line.