Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a batch file, how do I loop over strings with spaces in them?

In a batch file, how do I loop over strings with spaces in them?

For example, I have:

for %%P in (Test 1,Test 2,Test 3) do (
echo %%P
)

The output I get is

Test
1
Test
2
Test
3

instead of the output I am hoping for:

Test 1
Test 2
Test 3

if I add quotes I get

"Test 1"
"Test 2"
"Test 3"

which I don't want either. Any ideas?

like image 405
Roland Rabien Avatar asked Mar 28 '16 23:03

Roland Rabien


2 Answers

for /? has your answers.

%~I         - expands %I removing any surrounding quotes (")

So you'd implement it like this:

FOR %%P IN ("Test 1","Test 2","Test 3") DO (echo %%~P)
like image 73
Wes Larson Avatar answered Oct 06 '22 00:10

Wes Larson


@Wes Larson beat me to it, but here are other methods to split the strings without needing individual quotes;


Assuming there is only ever 3 strings to split;

for /f "tokens=1,2,3 delims=," %%G in ("Test 1,Test 2,Test 3") do (
    echo %%~G
    echo %%~H
    echo %%~I
)

Or my favorite;

set "string=Test 1,Test 2,Test 3"
set "chVar=%string%"
:reIter
for /f "tokens=1* delims=," %%G in ("%chVar%") do (echo %%G & set "chVar=%%H")
if defined chVar (goto :reIter)

And an odd but optional;

set "string=Test 1,Test 2,Test 3"
set string=%string: =_%
for %%G in (%string%) do call :replace "%%~G"
pause
exit

:replace
set "chVar=%~1"
echo %chVar:_= %
goto :eof
like image 42
Bloodied Avatar answered Oct 05 '22 23:10

Bloodied