I'm running a series of simulations and, because I need to edit a few files after each simulation to run the next one, I wanted to automate this process.
I already found how to search and replace a specific string with another, but what I need is to change these strings dynamically, based on a file that I wrote that has multiple replacement strings.
This is what I have so far for a basic search and replace (it's a solution I found here):
@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "INTEXTFILE=Test.in"
set "OUTTEXTFILE=Test_out.in"
set "SEARCHTEXT=50kV"
set "REPLACETEXT=60kV"
for /f "delims=" %%A in ('type "%INTEXTFILE%"') do (
set "string=%%A"
set "modified=!string:%SEARCHTEXT%=%REPLACETEXT%!"
echo !modified!>>"%OUTTEXTFILE%"
)
del "%INTEXTFILE%"
rename "%OUTTEXTFILE%" "%INTEXTFILE%"
endlocal
And this is what I've attempted, based on my understanding of the syntax:
@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "SOURCEFILE=Test.txt"
set "INTEXTFILE=Test.in"
set "OUTTEXTFILE=Test_out.in"
set "SEARCHTEXT=50kV"
for /f "delims=" %%A in ('type "%SOURCEFILE%"') do (
set "REPLACETEXT=%%A"
for /f "delims=" %%B in ('type "%INTEXTFILE%"') do (
set "string=%%B"
set "modified=!string:%SEARCHTEXT%=%REPLACETEXT%!"
echo !modified!>>"%OUTTEXTFILE%"
)
set "SEARCHTEXT=%%A"
del "%INTEXTFILE%"
rename "%OUTTEXTFILE%" "%INTEXTFILE%"
)
endlocal
However, this simply deletes the string I'm searching for (at least when all the instructions have been executed). What am I doing wrong here?
REPLACETEXTwithin the same block of code using immediate (%-)expansion rather than delayed expansion. Since, as per my understanding,Test.txtjust contains a single replacement string, read it before you readTest.in), so put the closing)of your firstfor /Floop before the second loop (rather than nesting the latter within the former)…Test.txtcontains 21 replacement strings. The idea is to run the simulation and save the results (using the same batch file; I excluded that code because it'd be meaningless for this problem), replace the necessary strings, and then run a new simulation. Were it just one replacement string, the solution I found would've worked just fine. However, I looked into delayed expansion and I fixed the problem. The only issue now is that thefor /fsearches an empty line in the.txtfile. How can I get it to stop?set "SEARCHTEXT=%%A", so multiple replacement strings make sense now… Anyway,set "modified=!string:%SEARCHTEXT%=%REPLACETEXT%!"is the problem then due to immediate expansion and the fact that delayed expansion cannot be nested; however, you could use anotherfor /Floop to achieve another layer of expansion:for /F "delims=" %%S in ("!SEARCHTEXT!=!REPLACETEXT!") do set "modified=!string:%%S!"…