how to set variables inside for-cycle

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
twistedmind
Posts: 2
Joined: 25 Aug 2021 08:07

how to set variables inside for-cycle

#1 Post by twistedmind » 25 Aug 2021 08:15

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
Last edited by Squashman on 25 Aug 2021 11:40, edited 1 time in total.
Reason: MOD EDIT: Please use code tags.

Squashman
Expert
Posts: 4486
Joined: 23 Dec 2011 13:59

Re: how to set variables inside for-cycle

#2 Post by Squashman » 25 Aug 2021 11:43

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!

twistedmind
Posts: 2
Joined: 25 Aug 2021 08:07

Re: how to set variables inside for-cycle

#3 Post by twistedmind » 25 Aug 2021 17:15

Thank you Squashman, you're right! I had tried with some ! but not correctly... your code is right and now it works. :D

Post Reply