How to expand variable in another variable with string substitution?

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Lowsun
Posts: 29
Joined: 14 Apr 2019 17:22

How to expand variable in another variable with string substitution?

#1 Post by Lowsun » 11 Jan 2020 15:19

Sorry about the confusing title, but I couldn't think about any other way to word it. Basically, I have some variables, for example:

Code: Select all

SET var[1]=12
SET var[2]=23
And another one, which contains the "var" prefix, but not that specific number, like:

Code: Select all

SET displayvar=%var[#]%
I'm trying to use it like:

Code: Select all

SET /A var=%displayvar:#=1%
To hopefully get the value of %var[1]%, but obviously it's already been expanded when it was SET above, so it gives nothing. I've tried doubling the %% and using CALL SET, but so far to no avail. Using DELAYEDEXPANSION isn't an option either, since I'm substituting variables with delayed expansion already.

Any tips or guidance would be much appreciated.

Thanks in advance, Lowsun :)

Eureka!
Posts: 136
Joined: 25 Jul 2019 18:25

Re: How to expand variable in another variable with string substitution?

#2 Post by Eureka! » 11 Jan 2020 20:57

With delayedexpansion enabled:

Code: Select all

setlocal enabledelayedexpansion
SET var[1]=12
SET var[2]=23

set #=1
SET displayvar=!var[%#%]!
set displayvar

With delayedexpansion disabled:

Code: Select all

setlocal 
SET var[1]=12
SET var[2]=23

set #=1
call SET displayvar=%%var[%#%]%%
set displayvar
Using your substitution method:
(Why the extra complication?)

Code: Select all

setlocal
SET var[1]=12
SET var[2]=23

set step1=%%var[#]%%
set step2=%step1:#=1%
call set display=%step2%

set step
set display

dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

Re: How to expand variable in another variable with string substitution?

#3 Post by dbenham » 11 Jan 2020 21:36

Your technique can work if you simply define displayvar properly. It works because SET /A can expand a variable on its own.\

Code: Select all

@echo off
setlocal
SET var[1]=12
SET var[2]=23
set "displayvar=var[#]"
set /a var=%displayvar:#=1%
echo %var%
--OUTPUT--

Code: Select all

12
But why on earth are you structuring things this way :?: :?

Lowsun
Posts: 29
Joined: 14 Apr 2019 17:22

Re: How to expand variable in another variable with string substitution?

#4 Post by Lowsun » 11 Jan 2020 21:49

Thanks Eureka and dbenham. I ended reworking all the code I was doing, since it was getting unwieldy down the line. Turns out I was over complicating a lot of stuff. But thanks for taking the time help :D

Post Reply