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).
Use Measure-Object to Get the String Length of a Variable in PowerShell. The Measure-Object cmdlet calculates the numeric properties of certain types of objects in the PowerShell. It counts the number of string objects' words, lines, and characters.
When you need to search through a string or log files in Linux we can use the grep command. For PowerShell, we can use the grep equivalent Select-String . We can get pretty much the same results with this powerful cmdlet. Select-String uses just like grep regular expression to find text patterns in files and strings.
To count the total number of lines in the file in PowerShell, you first need to retrieve the content of the item using Get-Content cmdlet and need to use method Length() to retrieve the total number of lines.
Here's one method:
$FileContent = Get-Content "YourFile.txt" $Matches = Select-String -InputObject $FileContent -Pattern "/export" -AllMatches $Matches.Matches.Count
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With