4

In Powershell, how would you search each row in a text file for an array of patterns? Select-string's pattern can accept an array, but it returns a true value if any of the strings in the array are found. I need it to return true (or actually the lines) if ALL the strings in the array are found in the line. Thanks.

3 Answers 3

3

For matching an array of strings against an array of patterns I believe you need something like this:

$patterns = @( ... )

Get-Content sample.txt | % {
  $count = 0
  foreach ($p in $patterns) {
    if ($_ -match $p) { $count++ }
  }
  if ($count -eq $patterns.Length) { $_ }
}

or like this:

$patterns = @( ... )

$content = Get-Content sample.txt
foreach ( $line in $content ) {
  $count = @($patterns | ? { $line -match $_ }).Length
  if ( $count -eq $patterns.Length ) { $line }
}
Sign up to request clarification or add additional context in comments.

Comments

2

Off the top of my head

Get-Content file.txt | 
Where-Object {$_ -match $ptrn1 -and $_ -match $ptrn2 -and $_ -match $ptrn3}

Comments

1

Another couple of possibilities:

$patterns = 'abc','def','ghi'
$lines = 'abcdefghi','abcdefg','abcdefghijkl'


:nextline foreach ($line in $lines)
 {foreach ($pattern in $patterns)
  {if ($line -notmatch $pattern){continue nextline}
 }$line}

abcdefghi
abcdefghijkl

That will abandon further processing of a line as soon as any of the patterns fails to match.

This works on the entire line collection at once, rather that doing a foreach:

$patterns = 'abc','def','ghi'
$lines = 'abcdefghi','abcdefg','abcdefghijkl'

foreach ($pattern in $patterns)
{$lines = $lines -match $pattern}
$lines

abcdefghi
abcdefghijkl

Substitute your get-content for the test literals to populate $lines.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.