批处理如何转义/忽略“!”在启用延迟扩展的字符串变量中

时间:2018-07-23 10:49:15

标签: batch-file cmd file-rename delayedvariableexpansion

我必须用批处理重命名某些文件,但是在某些文件名中是引起语法错误的感叹号。有人对此有解决方案吗?

setlocal EnableDelayedExpansion
set i=0
for %%a in (*.xml) do (
 set /a i+=1
 ren "%%a" !i!.new
)

1 个答案:

答案 0 :(得分:2)

为避免使用感叹号,请在循环中切换延迟扩展,以便在扩展for元变量时将其禁用,并仅在实际需要时才启用,如下所示:

rem // Disable delayed expansion initially:
setlocal DisableDelayedExpansion
set i=0
for %%a in (*.xml) do (
    rem /* Store value of `for` meta-variable in a normal environment variable while delayed
    rem    expansion is disabled; since `for` meta-variables are expanded before delayed expansion
    rem    occurs, exclamation marks would be recognised and consumed by delayed expansion;
    rem    therefore, disabling it ensures exclamation marks are treated as ordinary characters: */
    set "file=%%~a"
    rem // Ensure your counter to be incremented outside of the toggled `setlocal`/`endlocal` scope:
    set /a i+=1
    rem // Enable and use delayed expansion now only for variables that it is needed for:
    setlocal EnableDelayedExpansion
    ren "!file!" "!i!.new"
    endlocal
)
endlocal