Windows – Echo of String with Double Quotes to Output file using Windows Batch

batch-filewindows

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?

Best Answer

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:

\ & | > < ^ 
Related Topic