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.
source to share
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
source to share
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.
source to share
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.
source to share