1

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.

2 Answers2

1

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
mklement0
  • 382,024
  • 64
  • 607
  • 775
0

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