replace - bat script for replacing strings creates empty file -


i'm using bat file modify value in web.config httptransport httpstransport. works if direct output file. if try overwrite file creates empty file.

@echo off &setlocal set "search=httpstransport" set "replace=http123transport" set intextfile=d:\teste_bat\web.config set outtextfile=d:\teste_bat\webtemp.config  (for /f "delims=" %%i in ('findstr "^" "%intextfile%"') (     set "line=%%i"     setlocal enabledelayedexpansion     set "line=!line:%search%=%replace%!"     echo(!line!     endlocal ))>>"%outtextfile%"  del %intextfile%  rename %outtextfile% %intextfile% 

any e apreciated

the following code fails in case both intextfile , outtextfile point same file, because output redirection > prepares output file @ beginning, creates empty file, read findstr:

set "intextfile=d:\teste_bat\web.config" set "outtextfile=d:\teste_bat\web.config" > "%outtextfile%" (     /f "delims=" %%i in ('findstr "^" "%intextfile%"') (         set "line=%%i"         setlocal enabledelayedexpansion         set "line=!line:%search%=%replace%!"         echo(!line!         endlocal     ) ) 

replacing > >> not work, because appends new data original file.


to overcome this, have got 2 options:

  1. to write different file , replace original file new 1 @ end:

    set "intextfile=d:\teste_bat\web.config" set "outtextfile=d:\teste_bat\webtemp.config" > "%outtextfile%" (     /f "delims=" %%i in ('findstr "^" "%intextfile%"') (         set "line=%%i"         setlocal enabledelayedexpansion         set "line=!line:%search%=%replace%!"         echo(!line!         endlocal     ) ) move /y "%outtextfile%" "%intextfile%" 

    this recommended variant due better performance.

  2. to ensure file read before output redirection applied:

    set "intextfile=d:\teste_bat\web.config" set "outtextfile=d:\teste_bat\web.config" /f "delims=" %%i in ('findstr "^" "%intextfile%" ^& ^> "%outtextfile%" rem/') (     set "line=%%i"     setlocal enabledelayedexpansion     set "line=!line:%search%=%replace%!"     >> "%outtextfile%" echo(!line!     endlocal ) 

    this worse in performance since there multiple file access operations (appending file per each loop iteration due >>), prevents need of temporary file. portion > "%outtextfile%" rem/ depletes file after being read findstr, appended later in loop body.


Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -