Royce
Royce

Reputation: 585

Count specific string in text file using PowerShell

Is it possible to count specific strings in a file and save the value in a variable?

For me it would be the String "/export" (without quotes).

Upvotes: 28

Views: 85829

Answers (5)

Mohamed Amr
Mohamed Amr

Reputation: 47

The best solution I applied was

$count = (Select-String -Path "filepath" -Pattern "pattern" -AllMatches).Matches.Count

This one is memory optimized and accurate

Upvotes: 0

Bennett McElwee
Bennett McElwee

Reputation: 25760

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.

Upvotes: 8

TRM
TRM

Reputation: 7

grep -co vs grep -c

Both are useful and thanks for the "o" version. New one to me.

Upvotes: -4

GodEater
GodEater

Reputation: 3717

Here's one method:

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

$Matches.Matches.Count

Upvotes: 57

Leon Bambrick
Leon Bambrick

Reputation: 26306

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.

Upvotes: 14

Related Questions