Powershell search string for pattern array

In Powershell, how will you search each line in a text file for an array of templates? The Select-string pattern can take an array, but it returns the true value if any of the rows in the array are found. I need it to return true (or actually rows) if ALL rows in the array are found in the row. Thanks.

+4
source share
3 answers

To map an array of strings to 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 } } 
+3
source

On top of my head

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

Two more 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 

This will lead to further string processing as soon as any of the patterns matches.

This works in the entire line at once, but in what foreach does:

 $patterns = 'abc','def','ghi' $lines = 'abcdefghi','abcdefg','abcdefghijkl' foreach ($pattern in $patterns) {$lines = $lines -match $pattern} $lines abcdefghi abcdefghijkl 

Substitute your content for test literals to populate $ lines.

+1
source

All Articles