How to Use grep to Extract Last Occurrence in File


Often you may want to use the grep command in Bash to extract the line that contains the last occurrence of a particular pattern in a file.

You can use the following syntax to do so:

grep "Mavs" points.txt | tail -1

This particular example will return the line that contains the last occurrence of the pattern “Mavs” in the file named points.txt.

Note that we use grep “Mavs” points.txt to return all lines that contain “Mavs” and then we use tail -1 to specify that we only want to display the last line.

Feel free to replace tail -1 with tail -n to instead return the last n lines that contain the pattern.

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

Example: How to Use grep to Extract Last Occurrence in File

Suppose that we have a filed named points.txt that contains information about points scored by basketball players on various teams.

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

The first field in each line contains the name of the team the player is on and the second field contains the points scored by the player.

Suppose that we would like to return the last line in the file that contains “Mavs” somewhere in the line.

We can use the following syntax to do so:

grep "Mavs" points.txt | tail -1

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

grep last occurrence

Notice that this returns the last line in the file that contains the pattern “Mavs” somewhere in the line.

Note that we could change the value provided after the tail command to instead return the last n lines that contain this particular pattern:

grep "Mavs" points.txt | tail -2

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

grep last n occurrence of pattern in file

Notice that this returns the last two lines in the file that contains the pattern “Mavs” in the line.

Related Tutorials

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

How to Use grep to Get Line Number of Match
Bash: How to Filter for Lines in File that Start with Specific String
Bash: How to Filter CSV File Based on Column Value
Bash: How to Filter for Rows where Column is Not Empty

Leave a Reply