带有双引号的字符串回显使用Windows批处理输出文件

Geo*_*ndo 9 windows batch-file

我正在尝试使用Windows批处理文件重写配置文件.我循环遍历文件的行并查找我想用指定的新行替换的行.

我有一个'函数'将行写入文件

: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 
Run Code Online (Sandbox Code Playgroud)

问题是%Text%是一个嵌入双引号的字符串.然后就失败了.可能还有其他角色也会导致失败.如何才能使用配置文件中的所有文本?

Ofi*_*zon 12

尝试更换所有"Text^".

^是转义字符,因此"将被视为常规字符

你可以尝试以下方法:

: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
Run Code Online (Sandbox Code Playgroud)

其他可能导致错误的字符(您可以使用上述解决方案解决)是:

\ & | > < ^ 
Run Code Online (Sandbox Code Playgroud)