如何在 Powershell 中将 "foo" 和 "bar" 与 Select-String 匹配?

How to match for "foo" and "bar" with Select-String in Powershell?

如何在一条语句中 get the result 这些 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> 

希望在单个 pattern 中匹配“foo”和“bar”。

使用多个正面前瞻断言,每个断言扫描整个输入行(非贪婪地):

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

:

  • 这种方法也可以作为 wrapper 函数围绕 Select-String, named Select-StringAll, in this MIT-licensed Gist.

    使用
  • 假设你已经查看了链接的代码以确保它是安全的(我个人可以向你保证,但你应该经常检查),你可以直接安装它如下:

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

定义了这个函数,上面的命令等价于:

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

可能的解决方案或解决方案的方法:

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> 

感谢: