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"?

3

4 Answers 4

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%!
Sign up to request clarification or add additional context in comments.

1 Comment

One can do some useful stuff this way, like truncating strings GOPATH=!WD:%WD:*\src=\src%=!.
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

Comments

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

3 Comments

(that's a list, not an array). What if you need the third element only?
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%
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.
-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!

Comments

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.