Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 333
George Hernando Avatar asked Oct 11 '12 21:10

George Hernando


2 Answers

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:

\ & | > < ^ 
like image 182
Ofir Luzon Avatar answered Nov 05 '22 13:11

Ofir Luzon


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)

like image 43
NeronLeVelu Avatar answered Nov 05 '22 12:11

NeronLeVelu