What is the PowerShell equivalent of grep -f for matching patterns from a file?

I need to perform the same operation as grep --file=filename using PowerShell grep, where filename contains multiple regular expression patterns (one per line) to match in a text file.

I tried Select-String, but it doesn’t seem to support this option. How can I achieve this functionality in PowerShell?

You can replicate grep -f in PowerShell by first reading all the regex patterns from the file and then passing them to Select-String. Something like this works great:

$patterns = Get-Content patterns.txt
Select-String -Path input.txt -Pattern $patterns

Select-String accepts an array of patterns, so each line in patterns.txt is treated as a separate regex. This is the simplest and most direct equivalent of grep -f.

PowerShell doesn’t have a direct --file parameter like grep, but you can easily simulate it using a loop or pipeline. For example:

Get-Content patterns.txt | ForEach-Object {
    Select-String -Path input.txt -Pattern $_
}

This will run Select-String for each pattern line in your file. Works especially well when you want to handle matches individually or process results differently per pattern.

If you need behavior closer to grep -f with combined results and large pattern files, try:

$patterns = Get-Content patterns.txt | Where-Object { $_ -ne "" }
Get-Content input.txt | Where-Object { $line = $_; $patterns -match $line }

Or, even cleaner:

$patterns = Get-Content patterns.txt
Select-String -Path input.txt -Pattern $patterns -AllMatches

This approach gives you similar output to grep -f and supports regex too.