繁体   English   中英

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

[英]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 meta变量进行扩展时将其禁用,并仅在实际需要时才启用,如下所示:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM