PowerShell grep with Example

In this article, we discuss do we have any PowerShell grep cmdlet if yes then how to use the same to search for specific strings or regular expressions in one or more files like we have the ‘grep’ command in Unix-like operating systems.

 

PowerShell grep

 

PowerShell grep

In PowerShell, you can use the “Select-String” PowerShell cmdlet to search for a specific string or regular expression in one or more files. The Select-String in PowerShell is equivalent to the grep command.

Here’s an example of how you can use the Select-String cmdlet to search for the string “test” in a file named “examplegrep.txt”:

Select-String -Path "c:\psscript\examplegrep.txt" -Pattern "test"

Output –

 

PowerShell grep

The output returns all the lines where the “test” term is found in the given text file.

 

You can also search for multiple strings or regular expressions at the same time by specifying them as an array to the “-Pattern” parameter of the select-string command, see the below example –

Select-String -Path "c:\psscript\examplegrep.txt" -Pattern "Hi", "Hello"

 

In the above example, we have to search for a specific string in a single file you can also search for a string or regular expression in multiple files by specifying the path to a folder see the below example-

Select-String -Path " c:\psscript" -Pattern "test" -Include "*.txt" –Recurse

 

Here I have used the -Include parameter that specifies the types of files to search in, and the -Recurse parameter tells the cmdlet to search all subfolders within the specified folder.

 

You can also use the “-List” parameter to display the line number and context of each match, see the below example-

Select-String -Path " c:\psscript\examplegrep.txt" -Pattern "test" -List

 

You can also use the “-NotMatch” parameter to display the lines that do not match the pattern, see the below example-

Select-String -Path "c:\psscript\examplegrep.txt" -Pattern "test" –NotMatch

 

You can also use the “-Quiet” parameter to return True or False if the pattern found it returns true else it returns false, see below example-

Select-String -Path "c:\psscript\examplegrep.txt" -Pattern "test" –Quiet

 

You can also use the -AllMatches” parameter to return all matches, not only the first match in the line, see the below example-

Select-String -Path "c:\psscript\examplegrep.txt" -Pattern "test" –AllMatches

 

You can also use the “-SimpleMatch” parameter to use simple matching instead of regular expressions, see the below example-

Select-String -Path "c:\psscript\examplegrep.txt" -Pattern "test" -SimpleMatch

 

Conclusion

This is how you can use the select-string cmdlet which works as PowerShell grep to search specific terms in one single file or more than one file.