2016-08-02 85 views
1

我對此很陌生,所以我可能缺乏正確的語法。基本上我的問題是,我試圖將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 

任何人有任何想法如何解決這個問題?

回答

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

你擊敗了我整整10秒...:P – Filipus

+0

感謝一堆@SomethingDark和@Filipus! – ahchoo4u

+0

@ achoo4u - 樂於助人。如果我的解決方案爲您提供了答案,請點擊我答案旁邊的複選標記以將其標記爲已接受。 – SomethingDark

0

你只需要添加引號的變量值(因爲它們包含空格),並刪除它們,當你顯示,然後(使用%%〜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