Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count specific string in text file using PowerShell

Tags:

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).

like image 270
user3322838 Avatar asked Apr 27 '15 07:04

user3322838


People also ask

How do I count strings in PowerShell?

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.

Can you use grep in PowerShell?

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.

How do I count the number of lines in a text file using PowerShell?

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.


3 Answers

Here's one method:

$FileContent = Get-Content "YourFile.txt" $Matches = Select-String -InputObject $FileContent -Pattern "/export" -AllMatches  $Matches.Matches.Count 
like image 121
GodEater Avatar answered Sep 17 '22 13:09

GodEater


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.

like image 43
Leon Bambrick Avatar answered Sep 16 '22 13:09

Leon Bambrick


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.

like image 41
Bennett McElwee Avatar answered Sep 17 '22 13:09

Bennett McElwee