0

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

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

1 回答 1

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
于 2018-07-23T11:01:44.600 回答