1

I have this code:

@echo off
setlocal EnableDelayedExpansion

rem FILL ARRAY
set n=0
for %%a in (A B C) do (
   set fname[!n!]=%%a
   set /A n+=1
)

rem FIRST OUTPUT
for /L %%i in (0,1,2) do (
   echo !fname[%%i]!
)
echo/

rem SECOND OUTPUT
echo !fname[0]!
echo !fname[1]!
echo !fname[2]!
echo/

rem THIRD OUTPUT DOESN'T WORK
set n=0
for %%a in (A B C) do (
   echo !fname[!n!]!
   set /A n+=1
)

And get:

A
B
C

A
B
C

n
n
n

For some reasons I need output in third style and expect the same output like in first and second case but I can't understand what's wrong with it.

Update. Thank you, folks. I guess I've confused you a little but really I need to use this output in variable, so I've found this working solution, maybe it'll help somebody else:

rem THIRD OUTPUT WORKS
set n=0
for %%a in (A B C) do (
   for /f "tokens=2* delims==" %%x in ('set fname[!n!]') do (
   <... using %%x...>
   )
   set /A n+=1
)
rem %%x contains output now and can be used anywhere
Von
  • 15
  • 3
  • Please show me an actual example of the copy script, I know it is similar to this, but I need to see how you are determining meta variable `%%a` in order to give you a working script. I am getting idea you're overcomplicating something. – Gerhard Feb 24 '21 at 10:52
  • Thank you a lot. Could you appraise my solution if you have one more minute?)) It works but I think it can be more elegant. – Von Feb 24 '21 at 14:44
  • See https://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990 – Aacini Feb 24 '21 at 19:17
  • Can't see what's wrong? Consider `echo !fname[!n!]!`. This would be evaluated as `echo the currentvalue of "fname[" n the currentvalue of "]"` Neither variable `fname[` nor `]` is defined, hence replaced by *nothing* – Magoo Feb 24 '21 at 22:07

1 Answers1

1

You need another layer of parsing.

call echo %%fname[!n!]%%

or

for %%n in (!n!) do echo !fname[%%n]!

cures your third case.

Incorporated into your script:

@echo off
setlocal EnableDelayedExpansion

rem FILL ARRAY
set n=0
for %%a in (A B C) do (
   set fname[!n!]=%%a
   set /A n+=1
)

rem skip first and second output

rem THIRD OUTPUT WORKS
set n=0
for %%a in (D E F) do (
  call echo Copy "%%a" "%%fname[!n!]%%"
  for %%n in (!n!) do ECHO cOpy "%%a" "!fname[%%n]!"
  for /f "tokens=1* delims==" %%x in ('set fname[!n!]') do echo coPy "%%a" "%%y"
  set /A n+=1
)

of course use just one of the three lines (and don't forget to remove the ECHO after troubleshooting)

Stephan
  • 53,940
  • 10
  • 58
  • 91
  • Thank you a lot. Could you appraise my solution if you have one more minute?)) It works but I think it can be more elegant. – Von Feb 24 '21 at 14:43
  • works fine (I included it into my answer and made it safer). Perfectly valid approach (as they say: there is more than one way to skin the cat) – Stephan Feb 24 '21 at 15:12