Count specific string in text file using PowerShell

Here's one method:

$FileContent = Get-Content "YourFile.txt"
$Matches = Select-String -InputObject $FileContent -Pattern "/export" -AllMatches

$Matches.Matches.Count

If you're searching in a large file (several gigabytes) that could have have millions of matches, you might run into memory problems. You can do something like this (inspired by a suggestion from NealWalters):

Select-String -Path YourFile.txt -Pattern '/export' -SimpleMatch | Measure-Object -Line

This is not perfect because

  • it counts the number of lines that contain the match, not the total number of matches.
  • it prints some headings along with the count, rather than putting just the count into a variable.

You can probably solve these if you need to. But at least you won't run out of memory.


Here's a way to do it.

$count = (get-content file1.txt | select-string -pattern "/export").length

As mentioned in comments, this will return the count of lines containing the pattern, so if any line has more than one instance of the pattern, the count won't be correct.

Tags:

Powershell