dusty mehul
dusty mehul

Reputation: 13

PowerShell :: Regex Search in a File

Its my first day with PowerShell and i am trying to search no of occurrence of a REGEX pattern in a file and set this count into a variable. Please help me out.

Upvotes: 0

Views: 2483

Answers (3)

Moerwald
Moerwald

Reputation: 11254

$notMatchingLines = Get-Content "pathToYourFile" | Select-String "YourRegex" -NotMatch

If you want to know the number of lines not matching to your regex you can do:

$notMatchtingLines.Count

Practical example, return all lines from my vimrc not containing the word "set":

>$linesNotContaingSet = Get-Content .\_vimrc | Select-String "set" -NotMatch
>$LinesNotContaingSet.GetType()

 IsPublic IsSerial Name                                     BaseType
 -------- -------- ----                                     --------
 True     True     Object[]                                 System.Array

The result is an array:

 > $LinesNotContaingSet[0]
 call plug#begin()

The number of lines not matching:

 > $LinesNotContaingSet.Count

If you want to know what else you can do with the returned object(s), use Get-Member (alias =gm):

> $LinesNotContaingSet | gm


TypeName: Microsoft.PowerShell.Commands.MatchInfo

Name         MemberType Definition
----         ---------- ----------
Equals       Method     bool Equals(System.Object obj)
GetHashCode  Method     int GetHashCode()
GetType      Method     type GetType()
RelativePath Method     string RelativePath(string directory)
ToString     Method     string ToString(), string ToString(string directory)
Context      Property   Microsoft.PowerShell.Commands.MatchInfoContext  Context {get;set;}
Filename     Property   string Filename {get;}
IgnoreCase   Property   bool IgnoreCase {get;set;}
Line         Property   string Line {get;set;}
LineNumber   Property   int LineNumber {get;set;}
Matches      Property   System.Text.RegularExpressions.Match[] Matches {get;set;}
Path         Property   string Path {get;set;}
Pattern      Property   string Pattern {get;set;}

To get deeper into Powershell checkout MVA PowerShell Jumpstart videos.

Hope that helps

Upvotes: 1

user6811411
user6811411

Reputation:

Presuming with no you mean number:

for file content using Select-String, Measure-Object

$Count = (Select-String -Pattern 'pattern' -Path 'x:\path\file.txt'|Measure-Object).Count

For a variable and using .net

$Count = [regex]::matches($Content,'pattern').count

One hint here Select-String is by default case insensitive,
the dot net method not. You could prepend the pattern with (?i) for that.

Upvotes: 1

Esperento57
Esperento57

Reputation: 17462

Juste do it:

Select-String -Path "PathFile" -Pattern "YourRegex" -NotMatch

Upvotes: 0

Related Questions