As the title says I have a problem saving (and therefore printing) string variables in my bat script. The problem occurs when I try working with strings that start and/or end with '!'. Example:
@echo off
pause
setlocal ENABLEDELAYEDEXPANSION
for /r %%f in (*.png *.jpg *.gif *.webp *.jpeg) do (
set curr_name=%%~nxf
set curr_path=%%~dpf
@echo !curr_path!!curr_name!
@echo ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
)
pause
For file named !a.png and a!.png it prints out a.png and for !a!.png it just prints out .png. I've been trying to find answer for this but no luck. Sorry if I'm missing something obvious here and thanks for any tips!
CodePudding user response:
With delayed expansion enabled, this is expected behaviour. your shown use case does not require variables to be assigned - you could just use the relevant For variable modifiers.
If for some reason you need to use delayed expansion (for exmple performing substring modification), delayed expansion should be toggled on / off during the loop after the variable has been assigned:
Example:
@echo off
for /r %%f in (*.png *.jpg *.gif *.webp *.jpeg) do (
set "curr_name=%%~nxf"
set "curr_path=%%~dpf"
Setlocal enabledelayedexpansion
echo(!curr_path!!curr_name!
endlocal
@echo ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
)
pause