12

dos 批处理文件中通常的转义字符是插入符号,^. 但是对于百分比,%变量的分隔符,转义是加倍百分比:%%cd%%。在循环中使用参数扩展时情况会发生变化。for它不是像在循环外那样%%~dpnx0发出%~dpnx0,而是执行替换,发出D:\Scripts\foo.py

这是一个批处理文件演示:

@echo off
echo This is a pipe: ^|
echo Use this var for the current directory: %%cd%%
echo Use this to echo full path of running batch file: %%~dpnx0

for %%a in (foo.py baz.py) do (
  echo @python %%~dpnxa ^> %%~na.bat
  )

这些是我得到的结果:

This is a pipe: |
Use this var for the current directory: %cd%
Use this to echo full path of running batch file: %~dpnx0
@python d:\Scripts\foo.py > foo.bat
@python d:\Scripts\baz.py > baz.bat

但这就是我想要的:

This is a pipe: |
Use this var for the current directory: %cd%
Use this to echo full path of running batch file: %~dpnx0
@python %~dpnxa > foo.bat
@python %~dpnxa > baz.bat

我尝试过将百分比加倍、三倍和四倍,以及在整个过程中穿插插入符号,但均未成功。

4

2 回答 2

9

阻止 FOR 变量表达式的扩展是不可能的。如果 FOR 在定义变量 X 的情况下生效,则 FOR 扩展阶段将始终扩展%X

但是您可以将百分比隐藏在另一个 FOR 变量后面:)

以下给出了您正在寻找的结果:

@echo off
echo This is a pipe: ^|
echo Use this var for the current directory: %%cd%%
echo Use this to echo full path of running batch file: %%~dpnx0

for %%P in (%%) do for %%A in (foo.py baz.py) do (
  echo @python %%P~dpnxA ^> %%~nA.bat
)

FOR 变量具有全局范围(尽管它们只能在 DO 子句中访问)。这可能会导致一个潜在的问题。任何时候,只要您有一个在 FOR 循环中使用百分比文字的子例程,您就会面临意外结果的风险!在 CALL 之前发出的 FOR 语句会影响 CALL 例程中 FOR DO 子句的结果。

@echo off
for %%) in (Yikes!) do call :test
exit /b

:test
echo This works outside loop (confidence = 100%%)
for %%A in (1) do echo This does not work inside loop (confidence = 100%%)
for %%P in (%%) do for %%A in (1) do echo This works inside loop (confidence = 100%%P)
exit /b

这是输出

This works outside loop (confidence = 100%)
This does not work inside loop (confidence = 100Yikes
This works inside loop (confidence = 100%)
于 2012-12-04T19:46:17.427 回答
5

您可以使用延迟扩展或呼叫百分比扩展,或者像 dbenham 显示扩展另一个 FOR 变量。

setlocal EnableDelayedExpansion
set percent=%%
set "line=%%~dpnxa ^>"
for %%a in (foo.py baz.py) do (
  echo @python !percent!~dpnxa ^> %%~na.bat
  call echo @python %%line%% %%~nxa.bat
)
于 2012-12-04T21:54:58.863 回答