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
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 }
}
Comments
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.