Bash: How to Find Line Number of String in a File


You can use the following methods in Bash to find the line number where a specific string occurs in a file:

Method 1: Find Line Number of All Occurrences of String

grep -n "Nets" teams.txt | cut -f1 -d:

This particular example will return each line number in the file named teams.txt that contains the string “Nets” somewhere in the line.

Method 2: Find Line Number of First Occurrence of String

grep -n "Nets" teams.txt | head -n 1 | cut -f1 -d: 

This particular example will return the first line number in the file named teams.txt that contains the string “Nets” somewhere in the line.

Here is what the various commands do:

  • grep -n “Nets” : Print entire line with the line number of all lines that contain “Nets”
  • cut -f1 d: Return only the first field (-f1) from the output, specifying that the delimiter used for cutting should be a colon (-d:)
  • head -n 1: Only return the first occurrence

The following example shows how to use each of these methods in practice.

Example: How to Find Line Number of String in File Using Bash

Suppose that we have a file in our current directory named teams.txt that contains the names of various basketball teams.

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

Suppose that we would like to return each line number in the file that contains the string “Nets” anywhere in the line.

We can use the following syntax to do so:

grep -n "Nets" teams.txt | cut -f1 -d:

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

Bash find lines with string in file

From the output we can see that the string “Nets” occurs on lines 4, 7 and 10 in the file.

We could also use the following syntax to only return the first line number in the file that contains the string “Nets” somewhere in the line:

grep -n "Nets" teams.txt | head -n 1 | cut -f1 -d:

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

Bash find first line in file that contains string

Notice that this only returns the value 4, since this is the first line in the file that contains the string “Nets” in the line.

Feel free to use whichever method you prefer.

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