Using powershell to find files matching two different regular expressions

I want to find any file that can match two regular expressions, for example, all files that have at least one of bat

, hat

, cat

, and also the word noun

. This will be any file that can match both regular expressions [bhc]at

and noun

.

The regex to parameter select-string

only works in turn. You can seem to pass multiple patterns separated by commas ( select-string -pattern "[bhc]at","noun"

), but it matches either, not both.

+3


source to share


4 answers


Merging @mjolinor single get-content with @JNK optimized filtering gives:

dir | ?{ [string](gc $_) | ?{$_ -match "[bhc]at"} | ?{$_ -match "noun"} }

      



If you don't mind repeating, you can pass the results to select a row to see the contexts of those matches:

    | select-string -pattern "[bhc]at","noun" -allmatches

      

+2


source


You can always just use two filters:

dir | ? {(gc $_) -match '[bhc]at'} | ?{(gc $_) -match 'noun'}

      



This just gets all the objects that match the first criteria and checks that the result set is for the second. I guess this will be faster than checking both, as many files will only be checked once and then filtered out.

+5


source


It only needs one content to get it:

dir | where-object{[string](get-content $_)|%{$_ -match "[bhc]at" -and $_ -match "noun"}}

      

+3


source


I came up with a rather cumbersome but working one:

dir | where-object{((get-content $_) -match "[bhc]at") -and ((get-content $_) -match "noun")}

      

I can shorten this with aliases, but is there a more elegant way, preferably with less keystrokes?

My other option, if this becomes a frequent problem, seems to be creating a new cmdlet for the above snippet.

0


source







All Articles