PowerShell – Equivalent of `grep -r -l` (–files-with-matches)

greppowershell

In Powershell, how do I list all files in a directory (recursively) that contain text that matches a given regex? The files in question contain really long lines of incomprehensible text, so I don't want to see the matching line — just the filename.

Best Answer

You can use Select-String to search for text inside files, and Select-Object to return specific properties for each match. Something like this:

Get-ChildItem -Recurse *.* | Select-String -Pattern "foobar" | Select-Object -Unique Path

Or a shorter version, using aliases:

dir -recurse *.* | sls -pattern "foobar" | select -unique path

If you want just the filenames, not full paths, replace Path with Filename.


Explanation:

  1. Get-ChildItem-Recurse *.* returns all files in the current directory and all its subdirectories.

  2. Select-String-Pattern "foobar" searches those files for the given pattern "foobar".

  3. Select-Object-Unique Path returns only the file path for each match; the -Unique parameter eliminates duplicates.

Related Question