September 25, 2022


For computer aficionados

How to Print the First Match and Stop With Grep

grep is a lookup utility in Linux applied for matching information. By default, it will print out any line that matches, which may involve a good deal of output. If you only care about the initially match, you can restrict the output to just the 1st line.

Limiting Output with grep -m

The grep command has an -m or --max-count parameter, which can remedy this difficulty, but it might not get the job done like you’d count on.

This parameter will make grep stop matching after locating N matching strains, which will work wonderful as it will restrict the output to a single line, generally containing the 1st match. We can verify this with the -n flag to print the line numbers.

grep -m 1 "foo" file

On the other hand, this has some downsides you must be knowledgeable of. It does not end right after N matches, it stops just after N traces. This will trigger grep to match various moments on every line, which can be a dilemma when made use of with the -o flag, which prints just about every match on a new line.

Also, it is only N lines per file, so when utilized from a number of data files it will print out the very first matching line for every single file.

Making use of head To Restrict grep Output

The option is to pipe the output to a diverse command, head, which will simply just cut off the input after N lines. It is even now a little valuable to use -m 1 with grep though, as it will cease processing big information if a match is identified early.

grep "foo" file_one particular.txt | head -1

This performs with the -o flag to print only the initially match, even if there are several matches in a file:

Nevertheless, be mindful when utilizing this with a number of documents. Using head will print the initially matched line in any file. This can be a problem as grep prints output in the buy it processes the documents, and you may well not know the order the data files will be processed in unless of course you form them manually prior to passing them to grep.

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