How to Use grep to Get Line Number of Match


Often you may want to use the grep command in Bash to return the line numbers in a file that match a specific pattern.

You can use the following syntax to do so:

grep -n "Forward" athlete_data.txt | cut -f1 -d:

This particular example will return the line numbers in the file named athlete_data.txt that contain the pattern “Forward” somewhere in the line.

Here is what the various commands do:

  • We use the -n command to print the entire line with the line number of all lines that contain “Forward”
  • We use the cut command to return only the first field (-f1) from the output, specifying that the delimiter used for cutting should be a colon (-d:)

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

Example: How to Use grep to Get Line Number of Match

Suppose that we have a filed named athlete_data.txt that contains information about various basketball players.

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

The file contains information about the team name, position and conference that each player belongs to.

Suppose that we would like to return the line numbers in the file that contain the pattern “Forward” anywhere in the line.

We can use the following syntax to do so:

grep -n "Forward" athlete_data.txt | cut -f1 -d:

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

grep get line number of match

From the output we can see that line numbers 3 and 5 in the file contain the pattern “Forward” somewhere in the line.

We can manually verify that these two lines do indeed contain the pattern “Forward”:

  • Line 3: Celtics Forward East
  • Line 5: Rockets Forward West

Note: If no lines in the file contained the pattern that we searched for then the grep command would simply return nothing.

Related Tutorials

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

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
Bash: How to Extract Specific Columns from CSV File

Leave a Reply