Reputation: 153
I'm trying to rename my files to remove any characters that cause problems in scripts. This works well for ampersand and exclamation point but when the file has the percent sign it doesn't show up in the variable to begin with. How do I pass files with special characters via for loop?
for %%v in (*) do call :validate "%%v"
exit /b
:validate
set "original=%~nx1"
set "newtitle=%original:!=%"
set "newtitle=%newtitle:&=and%"
setlocal enabledelayedexpansion
set "newtitle=!newtitle:%%= percent!"
if not "%newtitle%"=="%original%" ren %1 "%newtitle%"
Upvotes: 2
Views: 1378
Reputation: 82307
Your problem is the line for %%v in (*) do call :validate "%%v", because the
call` starts the parser a second time and there all percents are evaluated a second time.
You should save the value into a variable and access these variable in your function instead.
setlocal DisableDelayedExpansion
for %%v in (*) do (
set "filename=%%~v"
call :validate
)
exit /b
:validate
setlocal EnableDelayedExpansion
set "original=!filename!"
set "newtitle=%original:!=exclam%"
set "newtitle=!newtitle:&=and!"
set "newtitle=!newtitle:%=percent!"
Upvotes: 2
Reputation: 34909
A possible way is to use delayed expansion:
set "newfilename=%filename:&=and%"
setlocal EnableDelayedExpansion
set "newfilename=!newfilename:%%= percent!"
endlocal
The %
-sign must be escaped by doubling it in a batch file.
Note that the variable is no longer available beyond the endlocal
command.
I used the quoted syntax, which is the safest way to define variables, even with white-spaces and special characters.
Upvotes: 2