FOR Loop using Variable in Array Name

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
TJDab
Posts: 2
Joined: 20 Nov 2018 05:52

FOR Loop using Variable in Array Name

#1 Post by TJDab » 20 Nov 2018 06:10

Hello everyone,

I am new here, because I have a question and after 30 minutes of searching, I would like to ask here for help.

I try to write a batch script to copy different files from a set of files to different folders.
Example: I have 50 images of a party and I would like to send image 1, 3 and 5 to person 1 and image 1,2, and 4 to person 2 and so on. Therefor I want to copy the files into new folders, one for each person. Since I have 600 pictures and 40 persons I thought I rather make a nice script copying all those images instead of copying each one manually.

So, my starting point was to set arrays of image IDs I want to copy and give to each person (Person_1, Person_2 etc)

Code: Select all

SET IMAGELISTE_PERSON_1=1 3 5
SET IMAGELISTE_PERSON_2=1 2 4
Then I wanted to loop through these arrays and use the values of the array to set my file names and to copy it.
But this means I have to treat the number behind the word person as a variable when looping, but still want to get the values set.

Code: Select all


:: LOOP THROUGH ALL PERSONS
FOR /L %%G IN (1,1,2) DO (
  
  ::LOOP THROUGH IMAGE IDs of SPECIFIC PERSON FROM IMAGELIST ARRAY DEFINED FOR EACH PERSON
  FOR /L %%A IN (%IMAGELIST_PERSON_%%G%) DO (

  SET FILENAME=PATH/FILENAME_%%A.jpg
  COPY FILENAME TARGET

  )
)
Set the file, folder and copy etc. works.
But the second FOR-Loop has problems.
I want to get A = 1, 3 and 5 for G = 1
and A = 1, 2 and 4 for G=2
But I am not able to get the values from the arrays in the 2nd FOR-Loop.

I hope you can understand what I want to do and I appreciate any help.
Thanks
TJ

aGerman
Expert
Posts: 3414
Joined: 22 Jan 2010 18:01
Location: Germany

Re: FOR Loop using Variable in Array Name

#2 Post by aGerman » 20 Nov 2018 11:25

You're trying to expand variables %IMAGELIST_PERSON_% and %G%. That's the reason why it doesn't work. Turn on delayed variable expansion.

Code: Select all

@echo off &setlocal
SET IMAGELISTE_PERSON_1=1 3 5
SET IMAGELISTE_PERSON_2=1 2 4

setlocal EnableDelayedExpansion
FOR /L %%G IN (1,1,2) DO (
  FOR %%A IN (!IMAGELISTE_PERSON_%%G!) DO (
    echo COPY "PATH\FILENAME_%%A.jpg" "TARGET_%%G"
  )
)
pause
Steffen

TJDab
Posts: 2
Joined: 20 Nov 2018 05:52

Re: FOR Loop using Variable in Array Name

#3 Post by TJDab » 21 Nov 2018 10:32

Steffen, thanks very much! It works nicely.
Have a great evening

Post Reply