2013-03-14 97 views
1

我想要做的應該是批次退伍軍人簡單。我有環境變量列表:批:從其他變量設置一個變量

核心-1 CORE2 CORE3等

我試圖將它們設置爲一個名爲HOSTS新的變量。每個變量應該由spaces.So分開的HOSTS =「核1 CORE2 CORE3」

for /L %%x in (1,1,20) do (
    IF "!CORE%x!"=="" (
     goto continue 
    ) 
    IF NOT "!CORE%x!"=="" ( 
     set HOSTS = "%HOSTS% !CORE%x!" 
    ) 
) 
:continue 

回答

1

如果我正確理解你的問題,你要幾個變量CORE1的內容串聯到CORE20 - 如果設置 - 成變量HOSTS,用空格分隔各個值。你可以做這樣的(我已經添加了一些示例值,以使一個可運行的例子):

@ECHO OFF 
SETLOCAL EnableDelayedExpansion 
SET CORE1=1 
SET CORE3=3 
SET CORE4=4 
SET CORE6=6 
SET CORE8=8 
SET CORE12=12 
SET CORE17=17 

for /L %%x in (1,1,20) do (
    IF "!HOSTS!"=="" ( 
     :: avoid leading space on first value 
     SET HOSTS=!CORE%%x! 
    ) ELSE (
     IF NOT "!CORE%%x!"=="" ( 
      SET HOSTS=!HOSTS! !CORE%%x! 
     ) 
    ) 
) 

ECHO %HOSTS% 

該腳本將輸出:

1 3 4 6 8 12 17 
+0

感謝的字母順序瓦爾CORE *的所有值!這完美的作品! – 2013-03-14 19:31:01

1

這對你的工作?

setlocal enabledelayedexpansion 
set inc=0 
:heck 
set /a "inc+=1" 
if defined CORE%inc% (
    set "HOSTS=%HOSTS% !CORE%inc%! 
    goto heck 
) 
rem remove leading space from %HOSTS% 
set HOSTS=%HOSTS:~1% 

這是一個更完整的測試腳本。

@echo off 
setlocal enabledelayedexpansion 

set CORE1=foo 
set CORE2=bar 
set CORE3=baz 
set CORE4=qux 
set CORE5=quux 
set CORE6=corge 
set CORE7=grault 
set CORE8=garply 
set CORE9=waldo 
set CORE10=fred 
set CORE11=plugh 
set CORE12=xyzzy 
set CORE13=thud 

set inc=0 
:heck 
set /a "inc+=1" 
if defined CORE%inc% (
    set "HOSTS=%HOSTS% !CORE%inc%! 
    goto heck 
) 
rem remove leading space from %HOSTS% 
set HOSTS=%HOSTS:~1% 

echo %HOSTS% 

輸出示例:

C:\Users\me\Desktop>test 
foo bar baz qux quux corge grault garply waldo fred plugh xyzzy thud 
0
@ECHO OFF 
SETLOCAL 
:: set 'COREn' to a value for testing 
FOR /l %%i IN (1,1,10) DO SET core%%i=str%%i 
:: 
(SET hosts=) 
FOR /f "tokens=2delims==" %%i IN ('set core') DO CALL :addval %%i 
ECHO hosts=%hosts% 
GOTO :eof 

:addval 
IF DEFINED hosts (SET hosts=%hosts% %1) ELSE (SET hosts=%1) 
GOTO :EOF 

你關心元件的精確序列?這將積聚在ENVVAR名

0
set HOSTS=%CORE1% 
for /L %%x in (2,1,20) do (
    if defined CORE%%x (
     set "HOSTS=!HOSTS! !CORE%%x!" 
    ) 
) 

安東尼