1

So I'm trying to print out the value of a variable in the form of (variable.variable). I can't figure out how to do it. The closest thing I got was:

echo %"%Dog.Index%"%

Which just printed out:

Dog.Index

And then I tried to add another set of % tags and that printed out:

%""%

Any help would be great! Thanks.

(EDITED)

I'm trying to basically make an array-like variable. So I want the value of Dog.1, Dog.2, Dog.3 printed out and assign them as such:

set Dog.%index%=(Value)

And %index% is just a counter that I increment. Trying "%Dog.index%" does not work, neither does %Dog%.%index% Thanks again.

0

3 Answers 3

2

You'll probably have to use delayed expansion of environment variables. The command SETLOCAL EnableDelayedExpansion initialises the mode, after which you can use the delayed expansion by enclosing variables in ! instead of %.

Here's an illustration of how it can be used:

@ECHO OFF
SETLOCAL EnableDelayedExpansion

ECHO Initialising...
FOR /L %%i IN (1,1,5) DO SET Dog.%%i=!RANDOM!

ECHO Displaying...
FOR /L %%i IN (1,1,5) DO ECHO %%i: !Dog.%%i!

SET index=3
ECHO Dog.%index% is !Dog.%index%!

Output:

Initialising...
Displaying...
1: 1443
2: 6940
3: 24198
4: 8054
5: 14092
Dog.3 is 24198

You can see that the last part of the script employs both the immediate and the delayed expansion. The immediate expansion replaces %index% with 3 and results in the variable name of Dog.3. Then the delayed expansion replaces the !Dog.3! expression with the value of the Dog.3 variable.

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

2 Comments

This is exactly what I needed! Thank you so much! It was starting to drive me a little crazy haha
+1 Nice! I wasn't familiar with the ! alternative and delayed expansion.
1

You're looking for something like this (in a batch/cmd file - note this requires at least XP, IIRC, and command extensions have to be enabled):

for /l %%i in (1, 1, 10) do set Dog%%i=%%i
for /l %%j in (10, -1, 1) do echo Dog%%j is %%%Dog%%j

(Note that the character following / is a lower-case L.)

For more info on for (pun intended), see MSDN TechNet.

Tested on Win7, BTW. Your mileage may vary. :)

Comments

1
set Dog=(Lassie WonderPup Fido Beethoven)
for %%i in %Dog% do echo %%i
pause

2 Comments

Hi kmb385, Yeah that's a little different than what I'm trying to do. What I need is strange. I edited my post if that helps clear up anything. Thanks for your help though!
@mike i update my post, but i just saw Ken White's and i believe his post captures what your after better than mine. Hopefully this resolves your issues.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.