This post will demonstrate various methods to search a string in multiple files.
How to Search a String in Files and Get the Names of Files Back in PowerShell?
These enlisted methods can be used to search a string in multiple files:
Method 1: Search a String in Multiple Files and Return File Names Using “select-string” Cmdlet
The string can be searched in multiple files using the “select-string” cmdlet. This cmdlet selects the strings and searches for text patterns in multiple files as follows:
Here:
- “Get-ChildItem” cmdlet is used to fetch the file from the specified location.
- “-recurse” flag forces the search to find the matching string in the sub-folders.
- “|” pipe operator is utilize to send the command’s output as the input of the next command.
- “-pattern” flag defines the specific string to be searched.
Output
The given output indicates that according to the specified pattern, the matched string with the relevant file names has been returned.
Method 2: Search a String in Multiple Files and Return File Names Using “sls” Cmdlet
“sls” is an alias of the “select-string” cmdlet and also works the same. The “sls” command is used with the “ls” cmdlet.
We have provided an example to demonstrate the working of the “sls” cmdlet to search a string in multiple files:
Here:
- “ls” cmdlet is used to list the files and folders.
- “-r” is the alias of the “-recurse” cmdlet used to force the search to find the string in sub-folders:
It can be observed that file names with the specified string have been fetched successfully.
Conclusion
To search a string in multiple files in PowerShell, use the “select-string” or the “sls” cmdlets. In the first method, use the “select-string” with the “Get-ChildItem” cmdlet, “-recurse” and “-pattern” flags, and pipeline (|) that joins the output of one command to the input of the other. In the “sls” command, use all the aliases of the commands used in the first approach. Because “sls” is the alias of the “select-string” cmdlet. This post has presented several methods for searching a string in multiple files.