Reputation: 23
I have to rename some files with a batch but in some filenames are exclamation marks which cause a syntaxerror. Does someone have a solution for that?
setlocal EnableDelayedExpansion
set i=0
for %%a in (*.xml) do (
set /a i+=1
ren "%%a" !i!.new
)
Upvotes: 1
Views: 492
Reputation: 34909
To avoid trouble with exclamation marks, toggle delayed expansion in the loop, so that it is disabled during expansion of for
meta-variables and enabled only when actually needed, like this:
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
Upvotes: 2