1

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.

user3708356
  • 39
  • 1
  • 6

3 Answers3

2

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)"
ncfx1099
  • 367
  • 1
  • 11
0

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

Select-String -Path C:\Logs\* -Pattern 'dog.*fence'
Dan Solovay
  • 3,134
  • 3
  • 26
  • 55
  • 1
    OP isn't very clear if the conditions ***are*** in the order `dog` then `fence`, if the other way around is possible, your RegEx won't match. –  Jun 17 '19 at 21:52
  • Fair point. I was trying to show you have access to the RegEx engine, but didn't think about the order question. – Dan Solovay Jun 18 '19 at 12:40
0

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"
day666
  • 1