26

视窗

根据帖子(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"

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

代码:

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

4 回答 4

50

这就是我会这样做的方式:

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

也就是说,在常规(NO /F 选项)命令中更改并处理Sun,Granite,Twilight"Sun" "Granite" "Twilight"引号括起来的每个部分。这种方法比基于 的迭代循环for要简单得多。for /F"delims=,"

于 2013-06-18T01:50:27.710 回答
26

我接受了Aacini的答案,只对其进行了轻微修改以删除引号,以便可以像在所需命令中一样添加或删除引号。

@echo off
set themes=Hot Sun,Hard Granite,Shimmering Bright Twilight
for %%a in ("%themes:,=" "%") do (
    echo %%~a
)
于 2016-04-05T17:10:29.757 回答
11

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

  1. 在子程序结束和主程序结束时需要 goto :eof,这样你就不会陷入子程序。
  2. tokens=1*(%%f 是第一个标记;%%g 是该行的其余部分)
  3. ~ in 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
    
于 2013-06-18T00:14:16.920 回答
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
于 2013-06-18T00:30:28.567 回答