13/09/2024

Tech Guru

Trusted Source Technology

How to Print the First Match and Stop With Grep

How to Print the First Match and Stop With Grep

How to Print the First Match and Stop With Grep

grep is a look for utility in Linux used for matching written content. By default, it will print out any line that matches, which might contain a lot of output. If you only care about the very first match, you can restrict the output to just the initially line.

Limiting Output with grep -m

The grep command has an -m or --max-count parameter, which can remedy this problem, but it might not operate like you’d assume.

This parameter will make grep stop matching following discovering N matching lines, which operates fantastic as it will limit the output to one particular line, normally containing the 1st match. We can confirm this with the -n flag to print the line figures.

grep -m 1 "foo" file

Nonetheless, this has some downsides you ought to be mindful of. It does not quit right after N matches, it stops after N lines. This will cause grep to match many periods on every single line, which can be a issue when utilised with the -o flag, which prints every single match on a new line.

Also, it’s only N lines for each file, so when utilized in opposition to a number of files it will print out the very first matching line for each and every file.

Working with head To Limit grep Output

The substitute is to pipe the output to a various command, head, which will simply just minimize off the input right after N traces. It’s even now a very little valuable to use -m 1 with grep though, as it will end processing significant information if a match is identified early.

grep "foo" file_just one.txt | head -1

This operates with the -o flag to print only the first match, even if there are numerous matches in a file:

Nevertheless, be thorough when utilizing this with several information. Making use of head will print the 1st matched line in any file. This can be a dilemma as grep prints output in the order it procedures the documents, and you may perhaps not know the purchase the data files will be processed in except if you sort them manually prior to passing them to grep.

Equally, you can also use tail to print the past matching line.