Variable in variable batch

倖福魔咒の 提交于 2020-01-06 08:16:11

问题


Alright, I need help here. I have done this before where you have variable1 (let's say it's eat1=apple), variable2 (this is eat2=orange), and variable3 (appaleorange=apple and orange). I need it to do this:

    echo Apple:%eat1%
    echo Orange:%eat2%
    echo Apple & Orange:%eat1%%eat2%

Now, you can see my problem. That above script wouldn't show the word and, only appleorange. That isn't my script and the reason I need this is because I have multiple variables with numbers in them. I have done this before and I forgot how... I know you can do a call and then multiple %'s.

In this case I want fterm variable to be fterm (not sure how to have it in there and not be a variable) and stermnum as a number that will be changed often on other parts of the script.

My code:

    set stermnum=1
    call set exsternum=%%fterm%%stermnum%%%
    echo Selected term:%stermnum% ^(%exsternum%^)

Does anyone know what to do? Thanks and sorry it was long :P

~Edit:I found it out... If it helps anyone I did: call set exsternum=%%fterm%stermnum%%

Sorry for posting this even though I figured it out so fast


回答1:


The OP appended a solution to the question, but it does not relate to the original question scenario, and it still has a bug.

Here is the OP's solution in terms of the original scenario:

set "eat1=apple"
set "eat2=orange"
set "appleorange=apple and orange"
call echo %%%eat1%%eat2%%%

For the actual code, I believe the OP wants to access an array of variables named fterm1, fterm2, fterm3, etc. And the number suffix is in a variable named stermnum.

call set exsternum=%%fterm%stermnum%%%

If fterm is itself a variable containing the base name of the array, then the solution becomes:

call set exsternum=%%%fterm%%stermnum%%%

But CALL is inefficient - Probably not noticeable with a single CALL, but it becomes painfully slow if executed thousands of times in a loop.

There is a much faster solution using delayed expansion. Delayed expansion must be enabled prior to being used.

Original scenario:

setlocal enableDelayedExpansion
set "eat1=apple"
set "eat2=orange"
set "appleorange=apple and orange"
echo !%eat1%%eat2%!

Actual code, interpretation 1:

setlocal enableDelayedExpansion
REM additonal code ...
set exsternum=!fterm%stermnum%!

Actual code, interpretation 2:

setlocal enableDelayedExpansion
REM additonal code ...
set exsternum=!%fterm%%stermnum%!


来源:https://stackoverflow.com/questions/14785765/variable-in-variable-batch

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!