Search code examples
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:

    • 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