Using powershell to find files that match two seperate regular expressions

折月煮酒 提交于 2019-12-06 00:33:27

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.

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

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

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

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.

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