3

I've used a for loop to split a string by spaces. I've also used a loop to make each word in its own variable such as var1=this, var2=is, var3=a, var4=test. That looks like "set var!count! = %%A"

That works. I just need to recall it. How do I do that? Logically, I think it would look like this: %var%count%%

Can someone explain to me how to get that? If I have the 'count' 1, what do I do to get "var1"?

4 Answers4

2

There is an easy way, you'll need to enable the delayed expansion, so first of all place setlocal enabledelayedexpansion, then use exclamation marks to access these variables. Your script should look like this:

@echo off
setlocal enabledelayedexpansion
:: Here comes your loops to set the variables
echo/!var%count%!
Rafael
  • 3,042
  • 3
  • 20
  • 36
0

When going through arrays in batch just use for /l:

@echo off
setlocal enabledelayedexpansion
var0 = A
var1 = B
var2 = C
var3 = D
var4 = E

for /l %%a in (0, 1, 4) do (
Echo var%%a = !var%%a!
)

Output:

var0 = A
var1 = B
var2 = C
var3 = D
var4 = E
Monacraft
  • 6,510
  • 2
  • 17
  • 29
0

I don't see why you would need to do that. What you are looking for seems to be an array variable. You could solve the issue with:

set variable=this;is;a;test
for %%a in (%variable%) do (echo %%a)

For each value you want separate it with a ";" The output of this code will be:

this
is
a
test
  • (that's a list, not an array). What if you need the third element only? – Stephan Apr 21 '20 at 10:16
  • It is also called an array, but indeed you are correct in questioning this since the only real way to get a certain value would be to make a for command with for %%i in (variable) do (%var2%+=1&if %var2% equ [number] echo %var2% –  Apr 21 '20 at 15:32
  • Another way you could do this which I personally like less is to use variablename and then [number] like set var[1]=1 && set var[2]=2 etc. –  Apr 21 '20 at 15:34
-1

If you want to print out the contents of var1 outside the for statement use

  Echo %var1%

To print out the contents of var1 inside the block first , delayed expansion needs to be enabled and instead of enclosing the variable references with percent signs , you use

   Echo !var1!
mordecai
  • 71
  • 4