How to Replace Every Occurrence of a String in a File


When working with files, sometimes we want to replace specified texts that appear all over the file In this article, we will show you some methods to replace every occurence of a text or string in a file.


Using Replace Method

Suppose we want to replace every occurence of string mystring with hello in a file named test.txt. This file is located at C:\Scripts folder. Then, we can use following script to replace those strings occurence:

(Get-Content C:\Scripts\test.txt) -replace 'mystring', 'hello' | Set-Content C:\Scripts\test.txt

There is also an alternative:

(Get-Content C:\Scripts\test.txt).Replace('mystring', 'hello') | Set-Content C:\Scripts\test.txt

Using .NET File Class

Since PowerShell supports .NET objects, we can use .NET File libraries to solve this problem in PowerShell, thus we can use combination of ReadAllText and WriteAllText method.

$content = [System.IO.File]::ReadAllText("C:\Scripts\test.txt").Replace("mystring","hello")
[System.IO.File]::WriteAllText("C:\Scripts\test.txt", $content)

Reading each line of the text, then replace them

We can also do a little more manual work, but still using replace method. First, we can get the content of the text. Then, we iterate each line of the text and replace the strings. To iterate the content, we can use Foreach-Object cmdlet.

(Get-Content C:\Scripts\test.txt) | Foreach-Object {$_ -replace 'mystring','hello'} | Set-Content C:\Scripts\test.txt


There are many ways to replace string occurrences in a file. We can use PowerShell replace method. But, since PowerShell supports .NET objects, we can also use .NET libraries such as the one from System.IO.File namespace.

comments powered by Disqus