Printing the First Match and Stopping with Grep In the early days of computing, there was no such thing as a word processor. Computers were programmed in assembly language, and output was printed to a terminal. For many people, this meant that printing was an essential part of their workflow. One of the earliest word processors was Grep, which was created by Ken Thompson and Dennis Ritchie at Bell Labs in the early 1970s. Grep allowed users to search through text files for specific lines or patterns. It was a very important tool for computer scientists and system administrators, who needed to find specific information quickly. Grep continued to be popular well into the 1990s, but its popularity began to decline around the same time that other word processors became available. Today, it is mostly used by historians and researchers who need to search through old text files. ..


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

The grep command has an -m or –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.

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.

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 grep.

Similarly, you can also use tail to print the last matching line.