如何批量循环逗号分隔的字符串?

时间:2013-06-18 00:01:05

标签: batch-file

根据帖子(dos batch iterate through a delimited string),我在下面编写了一个脚本但没有按预期工作。

目标:给定字符串“Sun,Granite,Twilight”,我想在循环中获取每个主题值,以便我可以使用该值进行一些处理。

当前输出不正确:

list = "Sun,Granite,Twilight"
file name is "Sun Granite Twilight"

第一次迭代应该是:

list = "Sun,Granite,Twilight"
file name is "Sun"

然后第二次迭代应该是“文件名是”花岗岩“等等。 我做错了什么?

代码:

set themes=Sun,Granite,Twilight

call :parse "%themes%"
goto :end

:parse
setlocal
set list=%1
echo list = %list%
for /F "delims=," %%f in ("%list%") do (
    rem if the item exist
    if not "%%f" == "" call :getLineNumber %%f
    rem if next item exist
    if not "%%g" == "" call :parse "%%g"
)
endlocal

:getLineNumber
setlocal
echo file name is %1
set filename=%1
endlocal

:end

4 个答案:

答案 0 :(得分:42)

这就是我这样做的方式:

@echo off
set themes=Sun,Granite,Twilight
echo list = "%themes%"
for %%a in ("%themes:,=" "%") do (
   echo file name is %%a
)

即,通过Sun,Granite,Twilight更改"Sun" "Granite" "Twilight",然后在常规(NO / F选项)for命令中处理引号中的每个部分。此方法比基于for /F的迭代"delims=,"循环简单得多。

答案 1 :(得分:21)

我接受了Aacini的答案,并稍微修改了它以删除引号,以便可以在所需的命令中添加或删除引号。

@echo off
set themes=Hot Sun,Hard Granite,Shimmering Bright Twilight
for %%a in ("%themes:,=" "%") do (
    echo %%~a
)

答案 2 :(得分:6)

我对您的代码做了一些修改。

  1. 需要转到:子程序结束时和主程序结束时的eof,这样你就不会陷入子程序。
  2. tokens = 1 *(%% f是第一个令牌; %% g是该行的其余部分)
  3. 〜在set list =%~1中删除引号,因此引号不会累积

    @echo off
    set themes=Sun,Granite,Twilight
    
    call :parse "%themes%"
    pause
    goto :eof
    
    :parse
    setlocal
    set list=%~1
    echo list = %list%
    for /F "tokens=1* delims=," %%f in ("%list%") do (
        rem if the item exist
        if not "%%f" == "" call :getLineNumber %%f
        rem if next item exist
        if not "%%g" == "" call :parse "%%g"
    )
    endlocal
    goto :eof
    
    :getLineNumber
    setlocal
    echo file name is %1
    set filename=%1
    goto :eof
    

答案 3 :(得分:0)

看起来需要“令牌”关键字......

@echo off
set themes=Sun,Granite,Twilight

call :parse "%themes%"
goto :end

:parse
setlocal
set list=%1

for /F "delims=, tokens=1*" %%f in (%list%) do (
    rem if the item exist
    if not "%%f" == "" call :getLineNumber %%f
    rem if next item exist
    if not "%%g" == "" call :parse "%%g"
)
endlocal
goto :end

:getLineNumber
setlocal
echo file name is %1
set filename=%1
endlocal 

:end