user3708356
user3708356

Reputation: 39

Using Powershell to find two different pattern matches in the same string and outputting the detected string

I'm trying to find a way to use powershell to search for two different string matches in the same line, and then to output that string.

For example, I want to find all sentences in a text file that contain the word "dog" and "fence".

So it would hit and detect / output

Sentence 1: "The dog jumped over the fence"

But not match on:

Sentence 2: "The dog went to the park"

Sentence 3: "They painted their fence white"

Select-String will do this for a single pattern, but I can't seem to get it to work for two pattern matches in the same line.

This for example would detect two patterns, but all three sentences since it's looks for the pattern individually:

Select-String -Path C:\Logs -Pattern 'Dog','Fence'

I know there's easy ways to do this with grep and awk, but I was hoping to find a way to accomplish this in PowerShell.

Upvotes: 1

Views: 1553

Answers (3)

day666
day666

Reputation: 1

I ended up just piping it into another select-string so I had 2 select strings. The first one filtered for dog and then second one filtered for fence, this works for any ordering.

Select-String -Pattern "dog" | Select-String -Pattern "fence"

Upvotes: 0

ncfx1099
ncfx1099

Reputation: 367

There is no Regex AND operator, but based on my limited knowledge of Regex and a quick search through of Stackoverflow (because this has to have had been asked before) I came across this which suggests that you might want to try this:

Select-String -Path C:\logs -Pattern "(?=.*dog)(?=.*fence)"

Upvotes: 2

Dan Solovay
Dan Solovay

Reputation: 3154

-Pattern accepts a regular expression, so this will work:

Select-String -Path C:\Logs\* -Pattern 'dog.*fence'

Upvotes: 0

Related Questions