如何在FOR循环中使用参数时转义百分比(%)?

时间:2012-12-04 18:23:59

标签: batch-file

dos批处理文件中的常用转义字符是插入符号^。但是对于百分比%(变量的分隔符),转义是将百分比加倍:%%cd%%。在for循环中使用parameter extensions时,情况会发生变化。而不是%%~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

我已尝试将百分比加倍,三倍和四倍,并在整个过程中插入插入符号,但都没有成功。

2 个答案:

答案 0 :(得分:7)

不可能阻止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语句可以影响CALLed例程中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%)

答案 1 :(得分:2)

您可以使用延迟扩展或调用百分比扩展,或者像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
)