I am writing a batch file script using Windows command-line environment and want to change each occurrence of some text in a file (ex. "FOO") with another (ex. "BAR"). What is the simplest way to do that? Any built in functions?
Windows – How to you find and replace text in a file using the Windows command-line environment
batch-filecommand-linescriptingtext-fileswindows
Related Question
- Windows – How to loop through each line in a text file using a windows batch file
- Windows – How to get current date/time on the Windows command line in a suitable format for usage in a file/folder name
- Windows – n equivalent of ‘which’ on the Windows command line?
- Bash – Find and Replace Inside a Text File from a Bash Command
- Mysql – How to get a list of user accounts using the command line in MySQL
- Windows – How to create an empty file at the command line in Windows
- Windows – List all environment variables from the command line
- Mysql – How to import an SQL file using the command line in MySQL
Best Solution
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 built-in. Here is the script I used to find/replace all instances of text in a file:
To explain it:
powershell
starts up powershell.exe, which is included in Windows 7-Command "... "
is a command line arg for powershell.exe containing the command to run(gc myFile.txt)
reads the content ofmyFile.txt
(gc
is short for theGet-Content
command)-replace 'foo', 'bar'
simply runs the replace command to replacefoo
withbar
| Out-File myFile.txt
pipes the output to the filemyFile.txt
-encoding ASCII
prevents transcribing the output file to unicode, as the comments point outPowershell.exe should be part of your PATH statement already, but if not you can 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