简体   繁体   中英

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?

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 .

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 .

  • 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:

'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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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