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.

Blaise
  • 143
  • 1
  • 1
  • 9
  • 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 `&` –  Mar 20 '17 at 00: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](http://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990) – Aacini Mar 20 '17 at 03:11
  • Thanks Aacini: this was very useful, particularly the !LIST%%i! which I used combined with LotPings' answer below to recursively display the lists. – Blaise Mar 20 '17 at 08:11

1 Answers1

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.

  • 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! – Blaise Mar 20 '17 at 08:51
  • Batching for more years I'd like to remember I still learn here on SO, kudos to @Aacini for the expansion with the for. –  Mar 20 '17 at 09:11