regexpowershelltextread-eval-print-loopselect-string

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.


Solution

  • Use multiple positive lookahead assertions that each scan the entire input line (non-greedily):

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

    Note:

    With this function defined, the equivalent of the above command is:

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