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?
The Ctrl + F and Command + F keyboard shortcut keys also work in Microsoft Excel and other spreadsheet programs to open the Find and Replace text box. In Microsoft Excel, older versions featured the Edit menu, and the Replace option is found in that menu.
Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input. txt. The s is the substitute command of sed for find and replace.
In computing, replace is a command that is used to replace one or more existing computer files or add new files to a target directory. Files with a hidden or system attribute set cannot be replaced using replace . The command lists all files that are replaced.
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:
powershell -Command "(gc myFile.txt) -replace 'foo', 'bar' | Out-File -encoding ASCII myFile.txt"
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 of myFile.txt
(gc
is short for the Get-Content
command)-replace 'foo', 'bar'
simply runs the replace command to replace foo
with bar
| Out-File myFile.txt
pipes the output to the file myFile.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
(Get-Content myFile.txt) -replace 'foo', 'bar' | Out-File -encoding ASCII myFile.txt
If you are on Windows version that supports .Net 2.0, I would replace your shell. PowerShell gives you the full power of .Net from the command line. There are many commandlets built in as well. The example below will solve your question. I'm using the full names of the commands, there are shorter aliases, but this gives you something to Google for.
(Get-Content test.txt) | ForEach-Object { $_ -replace "foo", "bar" } | Set-Content test2.txt
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With