Windows批处理中的变量嵌套

6
在Windows批处理中,你可以在一个变量内设置另一个变量吗?
解释:
所以%num%是在变量内的。
set num=5
set cnum=test
set h1=%c%num%%

能否让百分号的功能类似于括号? 输出结果应该是 h1=test

任何帮助将不胜感激。


1
请参见:https://dev59.com/62kw5IYBdhLWcg3wDWTL#10167990 - Aacini
3个回答

6

您在问题中的示例有些混乱,但我认为我明白您想要什么:

@echo off
setlocal

set C1=apple
set C2=orange
set C3=banana

set num=2


:: Inefficient way without delayed expansion
:: This will be noticeably slow if used in a tight loop with many iterations
call echo %%C%num%%%

:: The remaining methods require delayed expansion
setlocal enableDelayedExpansion

:: Efficient way 1
echo(
echo !C%num%!

:: Efficient way 2 - useful if inside parenthesized block
:: where %num% will not give current value
echo(
for %%N in (!num!) do echo !C%%N!

:: Showing all values via a loop
echo(
for /l %%N in (1 1 3) do echo !C%%N!

非常感谢!这正是我所需要的。 - Strictly No Lollygagging

4

您可能正在寻找 Call Set 命令。它将 cnum 设置为字符串 c1、c2、c3 等,每当 %num% 更改时它就会更改。然后,您可以使用 Call Set 将任何变量(例如 h1)分配为变量 cnum 代表的值。

@echo off
setlocal enabledelayedexpansion
    set c5=test
    set num=5

    :: set cnum to string "c5"
        set cnum=c%num%
    :: set h1 to to the existing variable c5 
        call set "h1=%%%cnum%%%"
        echo %h1%

2
你是想要类似这样的东西吗?
cls
@echo off
setlocal EnableDelayedExpansion
Set num=5
Set "c!num!=test"
Echo !c5!

更多有关延迟扩展的信息,请查看http://ss64.com/nt/delayedexpansion.html

cls
@echo off
setlocal EnableDelayedExpansion
set num=4
set c1=this is a demo
set c2=second example
set c3=third
set c4=this is the one I want
set c5=last
Echo !c%num%!

有点类似,只是相反的。我试图避免编写比我需要的更多的脚本,并调用根据某些条件变化的预定义变量,例如: - Strictly No Lollygagging
设置值为%start%number%%,其中%number%可以更改。 - Strictly No Lollygagging
已经定义了变量start1、start2、start3等,我只需要根据%number%变量加载特定的变量。 - Strictly No Lollygagging

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接