Reputation: 585
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
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
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
You can probably solve these if you need to. But at least you won't run out of memory.
Upvotes: 8
Reputation: 7
grep -co vs grep -c
Both are useful and thanks for the "o" version. New one to me.
Upvotes: -4
Reputation: 3717
Here's one method:
$FileContent = Get-Content "YourFile.txt"
$Matches = Select-String -InputObject $FileContent -Pattern "/export" -AllMatches
$Matches.Matches.Count
Upvotes: 57
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