2014-11-24 162 views
1

在windows批處理中,您可以在變量中設置變量嗎?變量中的Windows批處理變量

解釋:

所以%num%在變量內。

set num=5 
set cnum=test 
set h1=%c%num%% 

是否有可能使百分比像括號一樣工作? 輸出應該是h1 =測試

任何幫助,將不勝感激。

+1

參見:http://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990 – Aacini 2014-11-25 04:29:00

回答

1

你是否在這樣的事情?

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%! 
+0

排序,這只是顛倒了。我試圖避免腳本比我需要的多得多,並調用預定義的變量,這些變量根據特定條件而變化,例如: – Jonthemanman 2014-11-24 22:47:18

+0

set value =%start%number %%其中%number%可以更改。 – Jonthemanman 2014-11-24 22:48:40

+0

start1,start2,start3等已經定義好的變量,我只需要根據%number%變量加載某些變量。 – Jonthemanman 2014-11-24 22:49:16

2

你在你的問題的例子是一個爛攤子,但我想我明白你在找什麼:

@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! 
+0

非常感謝!這正是我需要的。 – Jonthemanman 2014-11-25 00:19:46

3

你可能會尋找呼叫設置命令。這將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%