How do I use Powershell to find text files containing all search terms/patterns, but not necessarily in the same line? Chaining Select-String only finds the terms contained in the same line.
Select-String -Path .\*.md -Pattern 'termA' | Select-String -Pattern 'termB' -List | Select-Object Filename
only finds files containing the terms in the same line. I want to find all files containing all terms/patterns I am looking for (should be whatever number of terms/patterns), anywhere in the file.
Test each file one at a time, but repeat Select-String
once per term - you can then discard the file as soon as any one term is not found:
$searchTerms = @(
'termA'
'termB'
)
Get-ChildItem -Path . -Filter *.md |Where-Object {
foreach($term in $searchTerms) {
$firstMatch = $_ |Select-String -Pattern $term |Select-Object -First 1
# we're not interested if any of the terms are missing
if (-not $firstMatch) { return $false }
}
# we've reached the end, all terms must have been found
return $true
}