PowerShell: How to Count Specific Words in a File


You can use the following syntax in PowerShell to count the number of occurrences of a specific word in a file:

(Select-String -Path "teams.txt" -Pattern "West" -AllMatches).Matches.Count

This particular example will count the number of times that the word “West” occurs in the text file named teams.txt.

Note: If the word “West” occurs multiple times on one line then each occurrence of the word will be counted.

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

Example: Count Specific Words in a File Using PowerShell

Suppose that we have a file named teams.txt in our current directory that contains information about various basketball teams.

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

Get-Content teams.txt

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

Suppose that we would like to count the number of times the word “West” occurs in the file.

We can use the following syntax to do so:

(Select-String -Path "teams.txt" -Pattern "West" -AllMatches).Matches.Count

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

PowerShell count occurrences of word in file

From the output we can see that the substring “West” occurs 4 times in the text file.

Feel free to replace “West” with any other word that you’d like to search for in your own file.

Related Tutorials

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

PowerShell: How to Find Position of Character in String
PowerShell: How to Replace Every Occurrence of String in File
PowerShell: How to Replace Text with Wildcard
PowerShell: How to Replace Special Characters in String

Leave a Reply