I'm attempting to rewrite a configuration file using a Windows Batch file. I'm looping through the lines of the file and looking for the line that I want to replace with a specified new line.
I have a 'function' that writes the line to the file
:AddText %1 %2
set Text=%~1%
set NewLine=%~2%
echo "%Text%" | findstr /C:"%markerstr%" 1>nul
if errorlevel 1 (
if not "%Text%" == "" (
setlocal EnableDelayedExpansion
(
echo !Text!
) >> outfile.txt
) else (
echo. >> outfile.txt
)
) else (
set NewLine=%NewLine"=%
setlocal EnableDelayedExpansion
(
echo !NewLine!
) >> outfile.txt
)
exit /b
The problem is when %Text% is a string with embedded double quotes. Then it fails. Possibly there are other characters that would cause it to fail too. How can I get this to be able to work with all text found in the configuration file?
Try replacing all "
in Text
with ^"
.
^
is escape character so the the "
will be treated as regular character
you can try the following:
:AddText %1 %2
set _Text=%~1%
set Text=%_Text:"=^^^"%
... rest of your code
REM for example if %1 is "blah"blah"blah"
REM _Text will be blah"blah"blah
REM Text will be blah^"blah^"blah
Other characters that could cause you errors (you can solve it with the above solution) are:
\ & | > < ^
In a windows batch shell (command) double quote are escape with ^
on standard command line BUT with a double double quote inside a double quoted string
echo Hello ^"Boy^"
echo "Hello ""Boy"""
(remark: second line will produce the external surrounding double quote in the output also)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With