在批处理文件中,如何循环遍历包含空格的字符串?

5
在批处理文件中,如何循环遍历包含空格的字符串?
例如,我有:
for %%P in (Test 1,Test 2,Test 3) do (
echo %%P
)

我得到的输出是:
Test
1
Test
2
Test
3

instead of the output I am hoping for:

Test 1
Test 2
Test 3

如果我加引号,我会得到什么。
"Test 1"
"Test 2"
"Test 3"

我也不想要那个。你有什么好主意吗?
2个回答

5

for /?可以回答你的问题。

%~I         - expands %I removing any surrounding quotes (")
所以您应该像这样实施它:
FOR %%P IN ("Test 1","Test 2","Test 3") DO (echo %%~P)

这只获取列表中的一个项目。 - Adambean

1

@Wes Larson比我先回答了,但这里有其他在不需要个别引号的情况下拆分字符串的方法;


假设只有三个字符串需要分割;
for /f "tokens=1,2,3 delims=," %%G in ("Test 1,Test 2,Test 3") do (
    echo %%~G
    echo %%~H
    echo %%~I
)

或者我的最爱;
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)

还有一个奇怪但可选的;

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接