How to Use grep to Only Print Second Match


You can use the grep command in Bash to return all lines from a file that match a particular pattern.

By default, grep will return all lines that match a pattern, but you can use the following syntax to return only the second match:

grep -m2 'Mavs' points.txt | tail -n1

This particular example will return only the second line that matches the pattern ‘Mavs’ in the filed named points.txt.

Here is what the various commands do:

  • -m: Specifies the number of matches to find before exiting. By using -m2, we are able to extract the first 2 matches in the file.
  • tail -n1: Specifies that we only want to print the last line from the previous input, which would be the second matching pattern in the file.

Note that you could change -m2 to a different number, such as -m3, to print only the third match instead.

The following example shows how to use this syntax in practice.

Example: How to Use grep to Only Print Second Match

Suppose that we have a file named points.txt that contains information about the team name and points scored by various basketball players.

We can use the cat command to view the contents of this file:

Suppose that we would like to return only the second line that matches the pattern ‘Mavs’ in the file.

We can use the following syntax to do so:

grep -m2 'Mavs' points.txt | tail -n1

The following screenshot shows how to use this syntax in practice:

grep print only second match

Notice that this returns only the second line that matches the pattern ‘Mavs’ in the file.

We can also change -m2 to a different number, such as -m3, to return the third line that matches ‘Mavs’ instead:

grep -m3 'Mavs' points.txt | tail -n1

The following screenshot shows how to use this syntax in practice:

grep print third matching pattern in file

Notice that this returns only the third line that matches the pattern ‘Mavs’ in the file.

Feel free to change -m2 to any number that you’d like to return the nth line that matches a particular pattern in a file.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

How to Use grep to Get Line Number of Match
How to Use grep to Extract Last Occurrence in File
How to Use grep with Case-Insensitive Matching
How to Use grep to List All Files Containing Specific String

Leave a Reply