批处理文件:for循环中的转义问号

Tie*_*ske 2 windows escaping batch-file

这个for循环(减少最小的例子);

@echo off
for %%a in (help -help --help /help ? /?) do ( 
   echo %%a 
)
Run Code Online (Sandbox Code Playgroud)

用'?'扼杀2个元素 字符.它输出

C:\Temp>test.bat
help
-help
--help
/help

C:\Temp>
Run Code Online (Sandbox Code Playgroud)

所以当它击中第一个'?'时它就退出循环.

这个集合的正确转义序列是什么?尝试了一堆东西,双引号,插入符号,反斜杠等,但似乎没有任何作用.

dbe*_*ham 5

另一种选择是在FOR/F字符串中使用换行符.FOR/F会将每一行视为一个独立的字符串.下面我展示了四种做同样事情的方法.

@echo off
setlocal enableDelayedExpansion

:: Define LF to contain a linefeed character
set ^"LF=^

^" The above empty line is critical. DO NOT REMOVE

:: Option 1
:: Embed linefeeds directly in the string literal
for /f %%A in ("help!LF!-help!LF!--help!LF!/help!LF!?!LF!/?") do (
  echo(%%A
)


echo(
:: Option 2
:: Define a variable with spaces and use search and replace
:: to substitue linefeeds
set "help=help -help --help /help ? /?"
for %%L in ("!LF!") do for /f %%A in ("!help: =%%~L!") do (
  echo(%%A
)


echo(
:: Option 3
:: Embed linefeed directly in string without LF variable
for /f %%A in (^"help^

-help^

--help^

/help^

?^

/?^") do (
  echo(%%A
)


echo(
:: Option 4
:: Embed linefeed directly in search and replace without LF variable
for /f %%A in (^"!help:^ ^=^

!^") do (
  echo(%%A
)
Run Code Online (Sandbox Code Playgroud)

我更喜欢选项2.我发现它是最容易阅读的,但仍然是紧凑的.

请注意,MC ND和我都使用echo(%%A.这是防止echo /?显示ECHO命令帮助所必需的.