2016-03-28 45 views
1

在一個批處理文件中,我如何循環字符串中的空格?在批處理文件中,如何循環字符串中的空格?

例如,我有:

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

我得到的輸出是

Test 
1 
Test 
2 
Test 
3 

,而不是我希望的輸出:

Test 1 
Test 2 
Test 3 

,如果我添加引號我獲得

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

我不想要。有任何想法嗎?

回答

3

for /?有你的答案。

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

所以,你會實現它是這樣的:

FOR %%P IN ("Test 1","Test 2","Test 3") DO (echo %%~P) 
1

@Wes拉爾森打我,但這裏有其他的方法,而不需要單獨的引號來分割字符串;


假設只有3個字符串需要拆分;

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 
相關問題