批处理如何 escape/ignore "!"在启用延迟扩展的字符串变量中

batch how to escape/ignore "!" in string variable with delayed expansion enabled

我必须批量重命名一些文件,但在某些文件名中是感叹号,这会导致语法错误。有人对此有解决方案吗?

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

为避免感叹号带来的麻烦,在循环中切换延迟扩展,以便在 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