1

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
)
aschipfl
  • 33,626
  • 12
  • 54
  • 99
Hans Wurst
  • 23
  • 2
  • 3
    As a supplement to the excellent answer provided by @aschipfl; if you don't have too many `.xml` files in the directory, you could forget about enabling delayed expansion and use a `Call` command to perform the expansion you need: `Call Ren "%%a" %%i%%.new`. – Compo Jul 23 '18 at 11:29

1 Answers1

2

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
aschipfl
  • 33,626
  • 12
  • 54
  • 99