2

In Windows CMD batch loop I would like to use dynamic variables: list1, list2 and list3 where the digit 1-3 is dynamic (ie: list&i), but I am struggling:

setlocal enabledelayedexpansion enableextensions
SET threads=3
set i=1

for /R %%x in (*.jpg) do  ( call set LISTNAME=LIST!i! & SET LIST!i!=!LISTNAME! "%%x" & set /A i=!i!+1  & if !i! gtr %threads% (set i=1))

echo "first" %LIST1%
echo "second" %LIST2%
echo "third" %LIST3%

The exact spot where I struggle is:

SET LIST!i!=!LISTNAME! "%%x" 

where I would like this for instance to be:

SET LIST1=!LIST1! "%%x"

However listname just translates to a string LIST1, never the variable LIST1. I also tried with no success:

SET LIST!i!=!LIST!i!! "%%x"

Purpose of the script: put the JPG file names in 3 lists EDIT to answer to first comment: files names distributed in round robin and separated with a space.

3
  • How do you want to distribute the pictures on the lists? Round robin? How should the file names in a list be separated, a space? If you already enclose the commands in parentheses there is no need to keep them on one line.with & Commented Mar 20, 2017 at 0:22
  • 4
    Use CALL SET LIST!i!=%%LIST!i!%% "%%x" or FOR /F %%i in ("!i!") DO SET LIST%%i=!LIST%%i! "%%x". This management is explained at this answer Commented Mar 20, 2017 at 3:11
  • Thanks Aacini: this was very useful, particularly the !LIST%%i! which I used combined with LotPings' answer below to recursively display the lists. Commented Mar 20, 2017 at 8:11

1 Answer 1

7

Assuming a round robin distribution you can easily get the list number with a modulus calculation. For demonstration purposes I only output filename.ext without drive:path.

@Echo off
setlocal enabledelayedexpansion enableextensions
Set /A "threads=3,i=0"
:: initialize List
For /L %%n in (1,1,%threads%) Do Set "List%%n="

for /R %%x in (*.jpg) do  ( 
  Set /A "n=i %% threads + 1,i+=1"
  for %%n in (!n!) do Set "List%%n=!List%%n! %%~nxx"
  rem call set "LIST!n!=%%LIST!n!%% %%~nxx"
)
echo "first " %LIST1%
echo "second" %LIST2%
echo "third " %LIST3%

Sample Output

"first "  watch_dogs1.jpg watch_dogs4.jpg watch_dogs7.jpg
"second"  watch_dogs2.jpg watch_dogs5.jpg watch_dogs8.jpg
"third "  watch_dogs3.jpg watch_dogs6.jpg watch_dogs9.jpg

EDIT Inserted the for variable type of delayed expansion.

Sign up to request clarification or add additional context in comments.

2 Comments

Very elegant! So the trick was in using "Call" in addition to the SET and the %%LIST!n!%%. I learnt a lot from your code!
Batching for more years I'd like to remember I still learn here on SO, kudos to @Aacini for the expansion with the for.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.