Page 1 of 1

how to set variables inside for-cycle

Posted: 25 Aug 2021 08:15
by twistedmind
Hi everyone,

I'm trying do a batch file to move automatically a set of photo files into the specific dir (to create) for the day of each photo.
I wrote this code but the SET instructions inside the for have no effect, it works with the value set outside the for-cycle, but this is not what I want...
Can anyone help me? Thanks

Code: Select all

@ECHO OFF
setlocal EnableDelayedExpansion 
cls

set nome=IMG_20180308_092220
set targetdir=%nome:~4,4%-%nome:~8,2%-%nome:~10,2%

for %%f in (.\IMG*.jpg) do (
	echo %%f
	echo %%~nf

	set nome=%%~nf
rem	set nome=IMG_20180308_092220
	set targetdir=%nome:~4,4%-%nome:~8,2%-%nome:~10,2%

	echo %nome%
	echo %targetdir%

	if not exist %targetdir% mkdir %targetdir%
	move %%f %targetdir%
)

pause

Re: how to set variables inside for-cycle

Posted: 25 Aug 2021 11:43
by Squashman
Well you have delayed expansion enabled but you are not using it. When using delayed expansion variables must be used with exclamation points instead of percent symbols.

Code: Select all

set nome=%%~nf
set targetdir=!nome:~4,4!-!nome:~8,2!-!nome:~10,2!
echo !nome!
echo !targetdir!

Re: how to set variables inside for-cycle

Posted: 25 Aug 2021 17:15
by twistedmind
Thank you Squashman, you're right! I had tried with some ! but not correctly... your code is right and now it works. :D