バッチでいくつかのファイルの名前を変更する必要がありますが、一部のファイル名には構文エラーの原因となる感嘆符があります。誰かがそれに対する解決策を持っていますか?
setlocal EnableDelayedExpansion
set i=0
for %%a in (*.xml) do (
set /a i+=1
ren "%%a" !i!.new
)
バッチでいくつかのファイルの名前を変更する必要がありますが、一部のファイル名には構文エラーの原因となる感嘆符があります。誰かがそれに対する解決策を持っていますか?
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