Search code examples
powershellfindstr

Find matching strings in txt file using pattern from other txt file using Powershell


I'm trying to search a txt file for a string match using another file which contains over 1000 lines of strings.

I have tried findstr using batch file but the search stops if the string contains spaces.

for /F %%i in (PatternList.txt) do (
echo Files containing %%i
findstr /C:%%i Data.txt
)

I have then tried to use Powershell:

So far I have this, but I think I need to loop somehow through the PatternList.txt and then use the list to find each string in the Data.txt.

$file_data = Get-Content C:\temp\test\PatternList.txt
Get-Content C:\temp\test\Data.txt | Where-Object { $_.Contains($file_data) }

Solution

  • You can use Select-String to search for more than one pattern.

    $file_data = Get-Content -Path D:\sample\patternlist.txt | Where-Object {$_}
    Select-String -Path D:\sample\Source.txt -Pattern @('(?!)'; $file_data)
    

    To deal with empty lines in the pattern list file you can use an added Where-Object and to deal with an empty file we can use the recommendation from Mathias.
    Kudos to Mathias. ;-)