简体   繁体   English

如何在 Powershell 中使用 Select-String 匹配“foo”和“bar”?

[英]How to match for “foo” and “bar” with Select-String in Powershell?

How to get the result of these Select-String matches in one statement?如何在一个语句中获得这些Select-String匹配的结果?

posh> 
posh> $string = Get-Content /home/nicholas/powershell/regex/text.txt
posh> $patternFoo = 'foo'                                           
posh> $patternBar = 'bar'
posh> $string | Select-String $patternFoo -AllMatches | Select-String $patternBar -AllMatches

jfkldafdjlfoofkldasjf jfkdla jfklsadfj fklsdfjbarfjkdlafj

posh> 
posh> $string


fjdksalfoofjdklsafjdk fjdkslajfd fdjksalfj fjdkaslfdls

jfkldafdjlfoofkldasjf jfkdla jfklsadfj fklsdfjbarfjkdlafj

posh> 

Looking to match "foo" and "bar" in a single pattern .希望在单个模式中匹配“foo”和“bar”。

Use multiple positive lookahead assertions that each scan the entire input line (non-greedily):使用多个肯定的前瞻断言,每个断言都扫描整个输入行(非贪婪):

'a bar foo ...' | Select-String '(?=.*?foo)(?=.*?bar)'

Note :注意

  • This approach is also available as a wrapper function around Select-String , named Select-StringAll , in this MIT-licensed Gist .在这个MIT 许可的 Gist中,这种方法也可用作Select-String周围的包装器function,名为Select-StringAll

  • Assuming you have looked at the linked code to ensure that it is safe (which I can personally assure you of, but you should always check), you can install it directly as follows:假设您已经查看了链接代码以确保它是安全的(我可以亲自向您保证,但您应该始终检查),您可以直接安装它,如下所示:

     irm https://gist.github.com/mklement0/356acffc2521fdd338ef9d6daf41ef07/raw/Select-StringAll.ps1 | iex

With this function defined, the equivalent of the above command is:定义了这个 function 后,上面的命令等效为:

'a bar foo ...' | Select-StringAll foo, bar

possible solution, or approach towards a solution:可能的解决方案,或解决方案的方法:

PS /home/nicholas> 
PS /home/nicholas> $pattern = '\w*(?<!foo)bar'                  
PS /home/nicholas> 
PS /home/nicholas> $string = Get-Content /home/nicholas/powershell/regex/text.txt
PS /home/nicholas> $pattern = '\w*(?<!foo)bar'                                   
PS /home/nicholas> $string | Select-String $pattern

jfkldafdjlfoofkldasjf jfkdla jfklsadfj fklsdfjbarfjkdlafj

PS /home/nicholas> 

thanks to:谢谢:

https://stackoverflow.com/a/9306228/4531180 https://stackoverflow.com/a/9306228/4531180

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM