1

I'm new to this, so I am likely lacking the proper syntax. Basically my problem is this, I am trying to match variables in array2 with elements in array1, but Batch is skipping the spaces in my variables. Not sure if I am articulating myself sufficiently here.

Here is my code:

@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

My output is this:

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

The output I'm expecting is this:

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

Anyone have any idea how to fix this?

2 Answers 2

1

You're very close!

When a regular for loop takes a string that contains spaces, it considers each word (or anything else separated by spaces) in that string to be a separate token... unless that string is surrounded by quotation marks. If the string is surrounded by quotation marks, the for loop uses the entire string at once.

The only other thing to mention is that the loop also considers the quotes to be part of the string and will print them unless you tell it not to by using the ~ flag.

@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
)
Sign up to request clarification or add additional context in comments.

3 Comments

You beat me by exactly 10 seconds... :P
Thanks a bunch @SomethingDark and @Filipus!
@achoo4u - Happy to help. If my solution provided you with an answer, please click the check mark next to my answer to mark it as accepted.
0

You just need to add quotes around your variable values (because they contain spaces) and remove them when you display then (using the %%~b in the :secondpart routine):

@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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.