PowerShell: How to Get Line Number of Matches


Often you may want to use PowerShell to get the line numbers of all lines in a file matching a specific pattern.

You can use the following syntax to do so:

(Get-Content players.txt | Select-String "Kings").LineNumber

This particular example returns all line numbers from the file named players.txt that match the pattern “Kings” somewhere in the line.

Note that multiple numbers will be returned if there are multiple lines that match the pattern.

Also note that if you leave out .LineNumber then the entire lines that contain “Kings” will be returned instead.

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

Example: How to Get Line Number of Matches in PowerShell

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

We can use the Get-Content cmdlet to view the contents of this file:

Suppose that we would like to find the line numbers in the file that match the pattern “Kings”. 

We can use the following syntax to do so:

(Get-Content players.txt | Select-String "Kings").LineNumber

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

PowerShell get line numbers of matches

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

Feel free to replace “Kings” with any other pattern that you would like to find.

Related Tutorials

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

PowerShell: How to Extract Text Between Two Strings
PowerShell: How to Replace Text with Wildcard
PowerShell: How to Replace Special Characters in String

Leave a Reply