Table of Contents
Using -replace
Operator
To replace a string in a text file:
- Use the
Get-Content
cmdlet to read the text file’s content. - Use the
-replace
operator to replace the old string with a new string in the given text file. - Use the
Set-Content
cmdlet to write the modified content to the text file.
1 2 3 |
This is a sample string. |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
$oldStr = "sample" $newStr = "test" $filePath = "E:\Test\file.txt" $fileContent = Get-Content $filePath Write-Host "Old File Content:`n$fileContent" $newFileContent = $fileContent -replace $oldStr, $newStr Set-Content $filePath $newFileContent $fileContent = Get-Content $filePath Write-Host "New File Content:`n$fileContent" |
1 2 3 4 5 6 |
Old File Content: This is a sample string. New File Content: This is a test string. |
First, we defined two variables named $oldStr
and $newStr
containing "sample"
, and "test"
string values; here, we wanted to replace the "sample"
with the "test"
string in the file.txt
file. Then, we stored the path of the file.txt
file in the $filePath
variable, which we will use to get and set content.
So, we used the Get-Content
cmdlet to retrieve the entire content of an item at the given location, which was file.txt
at $filePath
in the above code. Then, we stored the retrieved content in the $fileContent
variable. Remember, the Get-Content
cmdlet reads one line at a time for files and returns a collection of objects, each corresponding to the line of content. Then, we used the Write-Host
cmdlet to print the $fileContent
on the PowerShell console.
Now, we used the -replace
operator to replace the $oldStr
with $newStr
in the $fileContent
and stored the updated content in the $newFileContent
variable, which was further used with Set-Content
cmdlet to write the $newFileContent
in the file.txt
file located at $filePath
.
Again, we used Get-Content
to read the file at the specified $filePath
, stored the retrieved content in the $fileContent
variable, and used it with the Write-Host
cmdlet to display the updated content on the PowerShell console. Of course, we could check the updated content by manually opening the file.txt
but using Get-Content
is a more convenient approach to see the updated content on the console.
Let’s see another example to learn if the -replace
operator is case-insensitive by default.
1 2 3 |
This is a sample string. |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
$oldStr = "Sample" $newStr = "test" $filePath = "E:\Test\file.txt" $fileContent = Get-Content $filePath Write-Host "Old File Content:`n$fileContent" $newFileContent = $fileContent -replace $oldStr, $newStr Set-Content $filePath $newFileContent $fileContent = Get-Content $filePath Write-Host "New File Content:`n$fileContent" |
1 2 3 4 5 6 |
Old File Content: This is a sample string. New File Content: This is a test string. |
First, look at the file content provided above; we had a sample
string in the file.txt
. But, considering the above code snippet, we searched for the Sample
string to replace it with the test
, and the -replace
operator did it; see the above output. Hence proved that the -replace
operator is case-insensitive by default, which means the sample
and Sample
are the same strings for it.
We can alternatively use the replace
and -ireplace
operators because both replace the provided new strings with old strings and are case-insensitive.
We can use the -creplace
operator if we are bound to care for case sensitivity while doing replacement; see the following example.
1 2 3 |
This is a sample string. |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
$oldStr = "Sample" $newStr = "test" $filePath = "E:\Test\file.txt" $fileContent = Get-Content $filePath Write-Host "Old File Content:`n$fileContent" $newFileContent = $fileContent -creplace $oldStr, $newStr Set-Content $filePath $newFileContent $fileContent = Get-Content $filePath Write-Host "New File Content:`n$fileContent" |
1 2 3 4 5 6 |
Old File Content: This is a sample string. New File Content: This is a sample string. |
Observe the above output; no changes were made in the file content even after using the -creplace
operator. Why? Because we searched for the Sample
, but the file contained sample
, which was not the same for the -creplace
operator because it is case-sensitive by default.
Prefix the
-replace
operator withi
andc
as-ireplace
and-creplace
for case-insensitive and case-sensitive replacement. Note that-repalce
and-ireplace
are case-insensitive operators.
Let’s make this code more interesting and replace a string in the n
number of lines without losing the remaining content. See the following code snippet to exercise it. You can run the following code successfully using PowerShell version 3.0 or higher.
Use -replace
Operator to Replace a String in n
Lines
To replace a string in n
number of lines of the text file:
- Use
Get-Content
with the-TotalCount
parameter to read the first4
lines. - Use the
for
loop to iterate over the read content: - In each iteration:
- Use the
-replace
operator to replace the old string with a new string in the current line of the read content in step-1
- Use the
- Use
Get-Content
with the-Tail
parameter to read the last4
lines. - Use the
+=
operator to concatenate the modified content (first four lines) with the unchanged content (last four lines). - Use
Set-Content
to write content to the file at the given location.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
$oldStr = "sample" $newStr = "test" $filePath = "E:\Test\file.txt" $numberOfLines = 4 $fileContent = Get-Content $filePath -TotalCount 4 for ($i = 0; $i -lt $numberOfLines; $i++) { $fileContent[$i] = $fileContent[$i] -replace $oldStr, $newStr } $fileContent += Get-Content $filePath -Tail 4 Set-Content $filePath $fileContent |
1 2 3 4 5 6 7 8 9 10 |
This is a sample string1. This is a sample string2. This is a sample string3. This is a sample string4. This is a sample string5. This is a sample string6. This is a sample string7. This is a sample string8. |
1 2 3 4 5 6 7 8 9 10 |
This is a test string1. This is a test string2. This is a test string3. This is a test string4. This is a sample string5. This is a sample string6. This is a sample string7. This is a sample string8. |
This example is similar to the previous ones with a few modifications. First, we defined the $oldStr
, $newStr
, $filePath
, and $numberOfLines
to hold an old string, new string, text file’s path, and the number of lines that we will read.
Then, we used the Get-Content
cmdlet with the -TotalCount
parameter to read 4
lines from the file.txt
located at $filePath
; we stored the retrieved content in the $fileContent
variable.
Next, we used the for
loop to loop over each line of the $fileContent
. In each iteration, we used the index operator represented by []
to access the current line (i.e. $fileContent[$i]
), used the -replace
operator to replace the $oldStr
with $newStr
in that line, and updated that particular line in the $fileContent
.
Once we are done with the for
loop, we used the Get-Content
cmdlet with the -Tail
parameter as Get-Content $filePath -Tail 4
to read the last four lines from the file living at $filePath
, which we concatenated with $fileContent
using +=
operator. Finally, we used the Set-Content
cmdlet to write the $fileContent
to the file at $filePath
. You can observe the old and new content of the file.txt
above.
Similarly, we can replace a string in the last 4
lines.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
$oldStr = "sample" $newStr = "test" $filePath = "E:\Test\file.txt" $numberOfLines = 4 $fileContent = Get-Content $filePath -Tail 4 for ($i = 0; $i -lt $numberOfLines; $i++) { $fileContent[$i] = $fileContent[$i] -replace $oldStr, $newStr } $head = Get-Content $filePath -Head 4 $head += $fileContent Set-Content $filePath $head |
1 2 3 4 5 6 7 8 9 10 |
This is a sample string1. This is a sample string2. This is a sample string3. This is a sample string4. This is a sample string5. This is a sample string6. This is a sample string7. This is a sample string8. |
1 2 3 4 5 6 7 8 9 10 |
This is a sample string1. This is a sample string2. This is a sample string3. This is a sample string4. This is a test string5. This is a test string6. This is a test string7. This is a test string8. |
Could you have typos while specifying the file name for which you will be doing the replacement operation? In that case, you would not find the required string to be replaced. So, we must have conditionals to check if the file has the required string. If so, replace it; otherwise, let the user know about it. See the following example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
$oldStr = "samples" $newStr = "test" $filePath = "E:\Test\file.txt" $numberOfLines = 4 $check = Select-String -pattern $oldStr -path $filePath if($check -eq $null){ Write-output "String Not Found" } else{ $fileContent = Get-Content $filePath -Tail 4 for ($i = 0; $i -lt $numberOfLines; $i++) { $fileContent[$i] = $fileContent[$i] -replace $oldStr, $newStr } $head = Get-Content $filePath -Head 4 $head += $fileContent Set-Content $filePath $head } |
1 2 3 |
String Not Found |
We got a message as an output stating specified string is not found because the file.txt
contained sample
, not samples
. So how did we identify it? We used Select-String
with -pattern
and -path
parameters set to $oldStr
and $filePath
. This cmdlet returned $null
if the specified pattern was not found, which we stored in the $check
variable.
Further, we used the if
statement with the -eq
operator to check if the $check
equals $null
. If it is, print String Not Found
; otherwise, jump to the else
block and do the replacement operation. How are we replacing it? It is already covered in previous examples.
Using Replace()
Method
To replace a string in the given text file using PowerShell:
- Use the
Select-String
cmdlet to check if the specified pattern exists in the given file. Then, store the returned value in a variable. - Use the
-if
with the-eq
operator to check if the variable’s value (created in step-1) is equal tonull
. - If it is, use
Write-Host
to display a message and exit; otherwise, jump to theelse
block. - In the
else
block:- Use
Get-Content
to read the file content at the given path. - Use the
Replace()
method to replace the old string with a new string in the read content in the previous step. - Use
Set-Content
to write the modified content in the given file.
- Use
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
$oldStr = "sample" $newStr = "test" $filePath = "E:\Test\file.txt" $check = Select-String -pattern $oldStr -path $filePath if($check -eq $null){ Write-output "String Not Found" } else{ $fileContent = Get-Content $filePath $newFileContent = $fileContent.Replace($oldStr, $newStr) Set-Content $filePath $newFileContent } |
1 2 3 4 5 6 7 8 9 10 |
This is a sample string1. This is a sample string2. This is a sample string3. This is a sample string4. This is a sample string5. This is a sample string6. This is a sample string7. This is a sample string8. |
1 2 3 4 5 6 7 8 9 10 |
This is a test string1. This is a test string2. This is a test string3. This is a test string4. This is a test string5. This is a test string6. This is a test string7. This is a test string8. |
This example is similar to the ones learned in the previous section, but we used the Replace()
method this time. It also looked for the specified string and replaced it with another given string in the file. But, it is case-sensitive by nature; for this, Sample
and sample
are two different strings.
Using StreamReader
/StreamWriter
and File
Classes
To replace a string in the given text file using PowerShell:
- Use the
Select-String
cmdlet to check if the given pattern exists in the specified text file. Then, store the returned value in a variable. - Use the
-if
with the-eq
operator to check if the variable’s value (created in step-1) is equal tonull
. - If it is, use
Write-Host
to display a message and exit; otherwise, jump to theelse
block. - In the
else
block:- Use the
new()
method to create an object of theStreamReader
class. - Use the
ReadToEnd()
to read the entire content of the specified text file. - Use the
Close()
method to close the instance of theStreamdReader
class. - Use the
-replace
operator to replace the old string with a new string. - Use the
new()
method of theStreamWriter
class to create its object. - Use the
Write()
method to write the updated content. - Use the
Close()
method to close the instance of theStreamWriter
class.
- Use the
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
$oldStr = "sample" $newStr = "test" $filePath = "E:\Test\file.txt" $check = Select-String -pattern $oldStr -path $filePath if($check -eq $null){ Write-output "String Not Found" } else{ $streamReader = [System.IO.StreamReader]::new($filePath) $fileContent = $streamReader.ReadToEnd() $streamReader.Close() $fileContent = $fileContent -replace $oldStr, $newStr $streamWriter = [System.IO.StreamWriter]::new($filePath) $streamWriter.Write($fileContent) $streamWriter.Close() } |
1 2 3 4 5 6 7 8 9 10 |
This is a sample string1. This is a sample string2. This is a sample string3. This is a sample string4. This is a sample string5. This is a sample string6. This is a sample string7. This is a sample string8. |
1 2 3 4 5 6 7 8 9 10 |
This is a test string1. This is a test string2. This is a test string3. This is a test string4. This is a test string5. This is a test string6. This is a test string7. This is a test string8. |
We have already learned about the defined variables, code flow and conditionals. Here, we used the StreamReader
class to read the text file and the StreamWriter
class to write to the text file.
Similarly, we can use the File
class of the System.IO
namespace; it is more optimized than the StreamReader
and StreamWriter
classes. See the following example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
$oldStr = "sample" $newStr = "test" $filePath = "E:\Test\file.txt" $check = Select-String -pattern $oldStr -path $filePath if($check -eq $null){ Write-output "String Not Found" } else{ $fileContent = [System.IO.File]::ReadAllText($filePath) $fileContent = $fileContent -replace $oldStr, $newStr [System.IO.File]::WriteAllText($filePath, $fileContent) } |
1 2 3 4 5 6 7 8 9 10 |
This is a sample string1. This is a sample string2. This is a sample string3. This is a sample string4. This is a sample string5. This is a sample string6. This is a sample string7. This is a sample string8. |
1 2 3 4 5 6 7 8 9 10 |
This is a test string1. This is a test string2. This is a test string3. This is a test string4. This is a test string5. This is a test string6. This is a test string7. This is a test string8. |
Both solutions in this section do case-insensitive replacement because we used the -replace
operator, which is case-insensitive by default.
Using Pipeline to Replace All Occurrences
Using a pipeline is recommended if you need to replace all occurrences of the specified string in the given text file because it is a one-line solution.
1 2 3 4 |
(Get-Content "E:\Test\file.txt") -replace "sample", "test" | Set-Content "E:\Test\file.txt" |
1 2 3 4 5 6 7 8 9 10 |
This is a sample string1. This is a sample string2. This is a sample string3. This is a sample string4. This is a sample string5. This is a sample string6. This is a sample string7. This is a sample string8. |
1 2 3 4 5 6 7 8 9 10 |
This is a test string1. This is a test string2. This is a test string3. This is a test string4. This is a test string5. This is a test string6. This is a test string7. This is a test string8. |
We have already learned about the used cmdlets and operators. The new thing is the pipeline, which we use to forward data from the previous process to the next. In the above code, the pipeline represented by |
forwarded data retrieved after replacing a string of the read content to the Set-Content
cmdlet, which was written in the given file.
If you use this approach, don’t forget to enclose the Get-Content "E:\Test\file.txt"
within ()
; otherwise, the content will be read, one line at a time and flows down the pipeline until it reaches the Set-Content
cmdlet. This way, it will try to write to the same file already opened by the Get-Content
, and you will get an error.
That’s all about replace String in File.