批量FOR循环将变量视为数组(?)

时间:2016-08-02 16:28:57

标签: batch-file for-loop

我是新手,所以我可能缺乏正确的语法。基本上我的问题是这个,我试图将array2中的变量与array1中的元素进行匹配,但Batch正在跳过变量中的空格。不确定我是否在这里充分阐述自己。

这是我的代码:

@ECHO OFF

SET VAR1=One TWO THREE
SET VAR2=ALPHA BETA
SET VAR3=hello world

SET ARRAY1=ENTRY1 ENTRY2 ENTRY3
SET ARRAY2=%VAR1% %VAR2% %VAR3%

FOR %%a IN (%ARRAY1%) DO (
    CALL :secondpart
)
PAUSE
EXIT

:secondpart
FOR %%b IN (%ARRAY2%) DO (
ECHO %%a = %%b

)
EXIT /b

我的输出是:

ENTRY1 = One
ENTRY1 = TWO
ENTRY1 = THREE
ENTRY1 = ALPHA
ENTRY1 = BETA
ENTRY1 = hello
ENTRY1 = world
ENTRY2 = One
ENTRY2 = TWO
ENTRY2 = THREE
ENTRY2 = ALPHA
ENTRY2 = BETA
ENTRY2 = hello
ENTRY2 = world
ENTRY3 = One
ENTRY3 = TWO
ENTRY3 = THREE
ENTRY3 = ALPHA
ENTRY3 = BETA
ENTRY3 = hello
ENTRY3 = world

我期待的输出是:

ENTRY1 = One TWO THREE
ENTRY1 = ALPHA BETA
ENTRY1 = hello world
ENTRY2 = One TWO THREE
ENTRY2 = ALPHA BETA
ENTRY2 = hello world
ENTRY3 = One TWO THREE
ENTRY3 = ALPHA BETA
ENTRY3 = hello world

任何人都知道如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

你非常接近!

当常规for循环采用包含空格的字符串时,它会将该字符串中的每个单词(或其他任何用空格分隔的内容)视为单独的标记...除非该字符串被引号括起。如果字符串被引号括起,for循环会立即使用整个字符串。

唯一需要提及的是,循环还会将引号视为字符串的一部分,并将打印它们,除非您不使用~标志告诉它。

@ECHO OFF

SET VAR1="One TWO THREE"
SET VAR2="ALPHA BETA"
SET VAR3="hello world"

SET ARRAY1=ENTRY1 ENTRY2 ENTRY3
SET ARRAY2=%VAR1% %VAR2% %VAR3%

FOR %%a IN (%ARRAY1%) DO (
    CALL :secondpart
)
PAUSE
EXIT /B

:secondpart
FOR %%b IN (%ARRAY2%) DO (
ECHO %%a = %%~b
)

答案 1 :(得分:0)

您只需要在变量值周围添加引号(因为它们包含空格)并在显示时删除它们(使用:secondpart例程中的%%〜b):

@ECHO OFF

SET VAR1="One TWO THREE"
SET VAR2="ALPHA BETA"
SET VAR3="hello world"

SET ARRAY1=ENTRY1 ENTRY2 ENTRY3
SET ARRAY2=%VAR1% %VAR2% %VAR3%

FOR %%a IN (%ARRAY1%) DO (
    CALL :secondpart
)
PAUSE
goto :end

:secondpart
FOR %%b IN (%ARRAY2%) DO (
ECHO %%a = %%~b

)
:end
EXIT /b