Using powershell to find files that match two seperate regular expressions

时光怂恿深爱的人放手 提交于 2019-12-10 10:16:52

问题


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 as well as the word noun. That would be any file that can match both regular expressions [bhc]at and noun.

The regex parameter to select-string only seems to work on a line-by-line basis. It seems you can pass in multiple patterns delimited by commas (select-string -pattern "[bhc]at","noun") but it matches either, rather than both.


回答1:


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 result set for the second. I imagine it would be quicker than checking both as well since a lot of files will only get checked once, then filtered out.




回答2:


Here's a one that only requires one get-content:

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



回答3:


Merging @mjolinor's single get-content with @JNK's optimised filtering gives:

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

If you don't mind the repetition, you can pipe the results to select string to view the contexts of these matches:

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



回答4:


I have come up with the rather cumbersome-but-working:

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 making a new commandlet for the above snippet.



来源:https://stackoverflow.com/questions/9671196/using-powershell-to-find-files-that-match-two-seperate-regular-expressions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!