I have written a batch script to replace a string in text file.
Following is the script.
@echo off &setlocal
set \"search=%1\"
set \"replace=%2\"
This uses a helper batch file called repl.bat
- download from: https://www.dropbox.com/s/qidqwztmetbvklt/repl.bat
Place repl.bat
in the same folder as the batch file or in a folder that is on the path.
Repl.bat is a hybrid batch file using native Windows scripting and is far faster than a regular batch script.
The L
switch makes the text search and replace a literal string and I'd expect the 12 MB file to complete in several seconds on a modern PC.
@echo off &setlocal
set "search=%~1"
set "replace=%~2"
set "textfile=Input.txt"
set "newfile=Output.txt"
call repl.bat "%search%" "%replace%" L < "%textfile%" >"%newfile%"
del "%textfile%"
rename "%newfile%" "%textfile%"
Just download fart (find and replace text) from here
use it in CMD (for ease of use I add fart folder to my path variable)
here is an example:
fart -r "C:\myfolder\*.*" findSTR replaceSTR
this command will search in C:\myfolder and all sub-folders and replace findSTR with replaceSTR
-r means process sub-folders recursively.
fart is really fast and easy
A variant using Bat/Powershell (need .net framework):
replace.bat :
@echo off
call:DoReplace "Findstr" "replacestr" test.txt test1.txt
exit /b
:DoReplace
echo ^(Get-Content "%3"^) ^| ForEach-Object { $_ -replace %1, %2 } ^| Set-Content %4>Rep.ps1
Powershell.exe -executionpolicy ByPass -File Rep.ps1
if exist Rep.ps1 del Rep.ps1
echo Done
pause
Try this:
@echo off &setlocal
setlocal enabledelayedexpansion
set "search=%1"
set "replace=%2"
set "textfile=Input.txt"
set "newfile=Output.txt"
(for /f "delims=" %%i in (%textfile%) do (
set "line=%%i"
set "line=!line:%search%=%replace%!"
echo(!line!
))>"%newfile%"
del %textfile%
rename %newfile% %textfile%
endlocal
How about this, folks?
set search=%1
set replace=%2
set textfile=Input.txt
set line1=with open('%textfile%', 'rw') as f:
set line2=f.write(f.read().replace('%search%', '%replace%'))
python -c "%line1%%line2%"
Muhahaha
Edit:
In a crazy oneliner
python -c "with open('%textfile%', 'rw') as f: f.write(f.read().replace('%search%', '%replace%'))"
Give this a shot:
@echo off
setlocal
call :FindReplace "findstr" "replacestr" input.txt
exit /b
:FindReplace <findstr> <replstr> <file>
set tmp="%temp%\tmp.txt"
If not exist %temp%\_.vbs call :MakeReplace
for /f "tokens=*" %%a in ('dir "%3" /s /b /a-d /on') do (
for /f "usebackq" %%b in (`Findstr /mic:"%~1" "%%a"`) do (
echo(&Echo Replacing "%~1" with "%~2" in file %%~nxa
<%%a cscript //nologo %temp%\_.vbs "%~1" "%~2">%tmp%
if exist %tmp% move /Y %tmp% "%%~dpnxa">nul
)
)
del %temp%\_.vbs
exit /b
:MakeReplace
>%temp%\_.vbs echo with Wscript
>>%temp%\_.vbs echo set args=.arguments
>>%temp%\_.vbs echo .StdOut.Write _
>>%temp%\_.vbs echo Replace(.StdIn.ReadAll,args(0),args(1),1,-1,1)
>>%temp%\_.vbs echo end with