Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace every occurrence of a String in a file with PowerShell?

Tags:

powershell

Using PowerShell, I want to replace all exact occurrences of [MYID] in a given file with MyValue. What is the easiest way to do so?

like image 956
amateur Avatar asked Jun 17 '13 09:06

amateur


People also ask

How do I find and replace a string in PowerShell?

Using the Replace() Method The replace() method has two arguments; the string to find and the string to replace the found text with. As you can see below, PowerShell is finding the string hello and replacing that string with the string hi . The method then returns the final result which is hi, world .

How do I replace multiple characters in a string in PowerShell?

Replace Multiple Instance Strings Using the replace() Function in PowerShell. Since the replace() function returns a string, to replace another instance, you can append another replace() function call to the end. Windows PowerShell then invokes the replace() method on the original output.

How do I change a text file to a PowerShell script?

In the Save as type box, select a file type. For example, in the Save as type box, select 'PowerShell Scripts ( *. ps1 )'. Click Save.

How do you update a file in PowerShell?

To edit a file. txt in PowerShell, use the command notepad file. txt to open a graphical editor on Windows. If you need a simple file edit in your terminal without a graphical editor and without installation, you can use the command echo 'new content' > file.


Video Answer


1 Answers

Use (V3 version):

(Get-Content c:\temp\test.txt).replace('[MYID]', 'MyValue') | Set-Content c:\temp\test.txt 

Or for V2:

(Get-Content c:\temp\test.txt) -replace '\[MYID\]', 'MyValue' | Set-Content c:\temp\test.txt 
like image 119
Loïc MICHEL Avatar answered Nov 09 '22 17:11

Loïc MICHEL