2

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%"
Bricktop
  • 533
  • 3
  • 22

2 Answers2

2

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.

aschipfl
  • 33,626
  • 12
  • 54
  • 99
2

Your problem is the line for %%v in (*) do call :validate "%%v", because thecall` 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!"
jeb
  • 78,592
  • 17
  • 171
  • 225
  • This works, thank you! I am learning good stuff right here. BTW what are the implications if I like to build the part inside the parenthesis into a single line? Is it merely frowned upon? – Bricktop Jul 03 '17 at 09:53
  • @JohnnyRogers Do you mean `set "filename=%%~v" & call :validate`? It works, but it has no advantage. And it's harder to read – jeb Jul 03 '17 at 10:55
  • OK, roger that. – Bricktop Jul 03 '17 at 11:06