Implementing UNIX Grep functionality in PowerShell

The grep UNIX command allows you to find lines in files that contain key words or phrases. With this command, it is possible to perform a quick search of a file or directory without having to look at each file via a text editor or the UNIX more command.

To achieve same functionality in PowerShell, we can use Select-String cmdlet as shown below:

dir -Recurse *.* | Select-String -Pattern "Clear" | Select -Unique path

This will list all the files with path that contains “Clear” as string inside it.

Below command line will look for all the patterns available in Pattern.txt and will list the matching files with the path.

dir -Recurse *.* | Select-String -Pattern (Get-Content .\Pattern.txt) | Select -Unique path

–End of Article–

PS Script for replacing strings in the File

If you have a requirement to replace particular string in a file with some other string, it can be done using below PS statements.

(Get-Content .\test.txt | ForEach-Object {$_ -replace "CurrentUser","CurrentUser2"}) | Set-Content .\test.txt

Explanation –

1. First step is to read the content of the file

2. Pipe the output. Read each line by line and replace the required value. Note – “$_” means this row. It is equivalent to “this.” in .Net.

3. Please note “(“and “)” at the start of first command and end of second command respectively. It is needed as we want to send (Pipe) the full output to the last statement to set the content.

4. Finally set the updated content to the same file.