PowerShell: Search And Replace

We can use PowerShell to search for text and replace it in one or more files. We can use the Set-Content and the replace operator to achieve this. Let’s take a look at an example of replacing line numbers from a file with PowerShell.

1
2
3
1: This is line number 1
2: This is line number 2
3: This is line number 3

Let’s use the Set-Content and replace operator to replace the line numbers above.

1
2
3
$contents = Get-Content .\lines.txt
$contents = $contents = $contents -replace "^\s*\d+\s*:\s*",""
$contents | Set-Content ".\replaced.txt"

Above we use the Get-Content cmdlet to get the contents of the lines.txt file. We then assign the contents of the file to the variable $contents. Next, we use the -replace operator to replace the line numbers. Finally, we store the results of the replace operation in a file called replaced.txt. Above, we use the replace modifier which performs a case insensitive search and replace. There is also a creplace operator which performs a case sensitive search, replace operation.

Alternatively, we can perform the same operation in one line by using a Pipeline.

1
Get-content lines.txt | foreach-object {$_ -replace "^\s*\d+\s*:\s*",""} | Set-Content replaced.txt

After running the above command line numbers will be removed and a file containing the results of the operation will be created with the name replaced.txt.

1
2
3
This is line number 1
This is line number 2
This is line number 3

Conclusion

In this small tutorial we looked at how we can use Powershell to search and replace text within a file.