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?
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)
@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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With