PowerShell Replace String in File

PowerShell replace String in File

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.

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.

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.

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 with i and c 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 first 4 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 Get-Content with the -Tail parameter to read the last 4 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.

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.

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.

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 to null.
  • If it is, use Write-Host to display a message and exit; otherwise, jump to the else 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.

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 to null.
  • If it is, use Write-Host to display a message and exit; otherwise, jump to the else block.
  • In the else block:
    • Use the new() method to create an object of the StreamReader class.
    • Use the ReadToEnd() to read the entire content of the specified text file.
    • Use the Close() method to close the instance of the StreamdReader class.
    • Use the -replace operator to replace the old string with a new string.
    • Use the new() method of the StreamWriter class to create its object.
    • Use the Write() method to write the updated content.
    • Use the Close() method to close the instance of the StreamWriter class.

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.

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.

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.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *