批处理:从其他变量设置一个变量

时间:2013-03-14 15:47:12

标签: batch-file

我想要做的事情对于批处理退伍军人来说应该是简单的。我有一个环境变量列表:

核心-1 CORE2 CORE3等

我正在尝试将它们设置为一个名为HOSTS的新变量。每个变量都应该用空格分隔。所以HOSTS =“CORE1 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

4 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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名称

的字母顺序累积变量CORE *的所有值

答案 3 :(得分:0)

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

安东尼奥