How can you find and replace text in a file using the environnement de ligne de commande Windows?
A lot of the answers here helped point me in the right direction, however none were suitable for me, so I am posting my solution.
I have Windows 7, which comes with PowerShell intégré. Here is the script I used to find/replace all instances of text in a file:
powershell -Command "(gc myFile.txt) -replace 'foo', 'bar' | Out-File -encoding ASCII myFile.txt"
To explain it:
-
powershellstarts up powershell.exe, which is included in Windows 7 -
-Command "... "is a ligne de commande arg for powershell.exe containing the command to run -
(gc myFile.txt)reads the content ofmyFile.txt(gcis short for theGet-Contentcommand) -
-replace 'foo', 'bar'simply runs the replace command to replacefoowithbar -
| Out-File myFile.txtpipes the output to the filemyFile.txt -
-encoding ASCIIprevents transcribing the output file to unicode, as the comments point out
Powershell.exe should be part of your PATH statement already, but if not vous pouvez add it. The location of it on my machine is C:\WINDOWS\system32\WindowsPowerShell\v1.0
Update
Apparently modern windows systems have PowerShell built in allowing you to access this directly using
(Get-Content myFile.txt) -replace 'foo', 'bar' | Out-File -encoding ASCII myFile.txt