6

In this scenario:

@Echo off
Setlocal EnableDelayedExpansion

Set /a cnt=0

For /f "delims=" %%A in ('type "Test.txt"') do (
 Set /a "cnt=!cnt!+1"
 Set "var!cnt!=%%A"
)

Set /a "cnt2=0"

For /F %%B in ('Dir /a:d /b') Do (
 Set /a cnt2=!cnt2!+1
 Echo !%var%%cnt2%!
)

The "varcnt2" is composed of the variable "var" and "cnt2". And while the output I expect is:

AqNaTwIznj
dl4lMkYorm
gDtdyFmptd
MmrbIoJrUu
NszuIe8ZMt
QbWYTy7oqC
xUbBgKifGD
y0ouJH3EtK
ZSZxlSnBlQ
zVyRcCFXrM

(The content of Test.txt) I always get something else. I've tried placing the % and ! in various ways, but none have worked. Here are some examples:

!var!cnt2!! outputs cnt2

%var!cnt2!% outputs Echo is off

%var%!cnt2!% outputs 1 2 3 4 5 6 7 8 9 10

!%var%%cnt2%! outputs Echo is off

Last time I encountered this, I wrote this batch file to test this:

@Echo off
Setlocal EnableDelayedExpansion
set Hello1=a
Set Hello2=b
Set Hello3=c
set a=Hello

:Loop
set /a cnt=cnt+1
Echo !%a%%cnt%!
If %cnt% NEQ 3 Goto Loop
pause

And it worked, but in current scenario, it does not. I've also searched online and couldn't find much info since most questions were about people not knowing about DelayedExpansion.

The closest I could find was script 67 of this page: http://initscreen.developpez.com/tutoriels/batch/apprendre-la-programmation-de-script-batch/#LVI-B

But it doesn't help me understand what is incorrect about what i've written and so, any solution or explanation would be appreciated.

Nat108
  • 61
  • 3
  • 3
    Just as a comment: your variables are _not_ composed of _two_ other variables. The `var` part of the name is _constant_ (not variable). If such a part would be also a variable, then you would have a _series of different variables_ accessed each one by `cnt2` variable, that is the equivalent to a two-dimensional array... I suggest you to modify the title and use _"Variable composed of other variable in for loop"_. – Aacini Jul 28 '17 at 22:36
  • 2
    Change `Echo !%var%%cnt2%!` by `call Echo %%var!cnt2!%%` (slow) or `for %%C in (!cnt2!) do Echo !var%%C!` (better). This management is fully explained at [this answer](https://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990) – Aacini Jul 29 '17 at 02:56
  • The basic things are: you have to make sure that the inner variable (`cnt2`) is expanded *before* the outer one; since your code needs to work within a loop, you cannot use simple immediate `%` expansion; take a look at [Aacini's comment](https://stackoverflow.com/questions/45381346/variable-composed-of-other-variable-in-for-loop#comment77730790_45381346) and try to analyse how the expansion is done in the suggestions... – aschipfl Jul 31 '17 at 06:00

0 Answers0