1

对于批量退伍军人来说,我正在尝试做的事情应该很简单。我有一个环境变量列表:

核心 1 核心 2 核心 3 等

我正在尝试将它们设置为一个名为 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

4 回答 4

1

如果我正确理解了您的问题,您希望将多个变量的内容(如果已设置)连接CORE1CORE20一个变量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
于 2013-03-14T15:59:30.773 回答
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
于 2013-03-14T16:00:31.173 回答
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 名称的字母顺序累积 vars CORE* 的所有值

于 2013-03-14T16:04:53.920 回答
0
set HOSTS=%CORE1%
for /L %%x in (2,1,20) do (
   if defined CORE%%x (
      set "HOSTS=!HOSTS! !CORE%%x!"
   )
)

安东尼奥

于 2013-03-14T18:44:48.073 回答