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" set "textfile=Input.txt" set "newfile=Output.txt" (for /f "delims=" %%i in (%textfile%) do ( set "line=%%i" setlocal enabledelayedexpansion set "line=!line:%search%=%replace%!" echo(!line! endlocal ))>"%newfile%" del %textfile% rename %newfile% %textfile%
But for a 12MB file, it is taking close to 7 min. I want it to be under a minute. Can we make use of find or findstr command to reduce the time taken?
Represents a replaceable parameter. Use a single percent sign ( % ) to carry out the for command at the command prompt. Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> )
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
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