Reputation: 75
I'm trying to replace strings in filenames using a batch script but run into problems if the files have exclamation marks or ampersand.
Setlocal enabledelayedexpansion
Set "Pattern=[String_A]"
Set "Replace=[B_String]"
For %%a in (*.*) Do (
Set "File=%%~a"
Ren "%%a" "!File:%Pattern%=%Replace%!"
)
The code above works for filenames without those but I need help for the rest.
This is something I have to run multiple times (it's part of bigger script).
Any help is appreciated.
Upvotes: 1
Views: 524
Reputation: 82202
The problem is that the expansion in set "file=%%~a
will be only safe, if delayed expansion is disabled.
The solution is toggling the delayed expansion mode.
Setlocal DisableDelayedExpansion
Set "Pattern=[String_A]"
Set "Replace=[B_String]"
For %%a in (*.*) Do (
Set "File=%%~a"
Setlocal EnableDelayedExpansion
Ren "!file!" "!File:%Pattern%=%Replace%!"
endlocal
)
Upvotes: 1