11

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?

4

2 に答える 2

16

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:

\ & | > < ^ 
于 2012-10-14T16:42:45.180 に答える
1

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)

于 2016-02-25T12:30:31.780 に答える