Batch script to find and replace a string in text file without creating an extra output file for storing the modified file
Solution 1:
@echo off
setlocal enableextensions disabledelayedexpansion
set "search=%1"
set "replace=%2"
set "textFile=Input.txt"
for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
set "line=%%i"
setlocal enabledelayedexpansion
>>"%textFile%" echo(!line:%search%=%replace%!
endlocal
)
for /f
will read all the data (generated by the type
comamnd) before starting to process it. In the subprocess started to execute the type
, we include a redirection overwritting the file (so it is emptied). Once the do
clause starts to execute (the content of the file is in memory to be processed) the output is appended to the file.