I have a batch script which replaces several occurrences of a source string within a source text file with a user input string.
For this I use a slightly corrected version of this answer here: How to replace substrings in windows batch file
(This is not the accepted answer, the accepted one does alter the source file even more!) But I was only able to resolve a little "adds a space to every line"-bug, not the major problem of not being able to use source files with exclamation marks within!
For this remaining problem I researched some more and e.g. found (and tried the suggestions of) these topics:
- exclamation point being removed constantly in batch file
- Windows batch - Delayed expansion removes exclamation mark
Sadly these questions' solutions (of temporarily disabling the "delayed expansion") do not apply for me since there is a single line within my script which does need the "delayed expansion" AND has to process variable values with potential exclamation marks!
This is the line
SET modified=!string:%SEARCHTEXT%=%REPLACETEXT%!
which can be seen in its context following my first link.
As a short explanation: This line needs the delayed expansion to be functional since it resides within an if-else-block within a for-block. On the other hand the value of variable 'string' could contain exclamation marks since it scans through the source file, line by line.
Does anybody has an idea how I could resolve this?
EDIT:
According to the first comments I tried to enable the delayed expansions only for the necessary parts of the main loop (only where access to modified variable content is needed, using the "!"-operator). The whole main loop now looks like this:
setlocal disabledelayedexpansion
for /f "tokens=1,* delims=¶" %%A in ('"findstr /n ^^ %INTEXTFILE%"') do (
SET string=%%A
setlocal enabledelayedexpansion
for /f "delims=: tokens=1,*" %%A in ("!string!") do set "string=%%B"
if "!string!" == "" (
echo.>>%OUTTEXTFILE%
) else (
SET modified=!string:%SEARCHTEXT%=%REPLACETEXT%!
echo !modified!>> %OUTTEXTFILE%
)
endlocal
)
endlocal
Sadly this yields no benefit at all. This results in the same output file as when I had enabled the delayed expansions for the whole script.
Did I apply the given hints in a wrong way? (If I restrict the enabled range any further, I only get empty lines or other rubbish in the output.)