Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch script to find and replace a string in text file within a minute for files up to 12 MB

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?

like image 260
ananth joshi Avatar asked Apr 15 '14 14:04

ananth joshi


People also ask

What does %% mean in batch script?

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> )


1 Answers

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 
like image 53
Matt Williamson Avatar answered Sep 20 '22 17:09

Matt Williamson