如何批量循环逗号分隔的字符串?
视窗
基于帖子(dos batch iterate through a delimited string),我在下面写了一个脚本,但没有按预期工作.
Based on the post (dos batch iterate through a delimited string), I wrote a script below but not working as expected.
目标:给定字符串Sun,Granite,Twilight",我想在循环中获取每个主题值,以便我可以对该值进行一些处理.
Goal: Given string "Sun,Granite,Twilight", I want to get each theme value in loop so that I can do some processing with the value.
当前输出不正确:
list = "Sun,Granite,Twilight"
file name is "Sun Granite Twilight"
对于第一次迭代,它应该是:
For the first iteration it should be:
list = "Sun,Granite,Twilight"
file name is "Sun"
然后第二次迭代应该是文件名是花岗岩"等等.我做错了什么?
Then second iteration should be "file name is "Granite" and so on. What am I doing wrong?
代码:
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
我对您的代码进行了一些修改.
I made a few modifications to your code.
- 需要在子例程结束和主例程结束时使用 goto :eof 以免陷入子例程.
- tokens=1*(%%f 是第一个标记;%%g 是该行的其余部分)
~ in set list=%~1 删除引号,这样引号就不会累积
- Need goto :eof at end of subroutines and at end of main routine so you don't fall into subroutines.
- tokens=1* (%%f is first token; %%g is rest of the line)
~ in set list=%~1 to remove quotes so quotes don't accumulate
@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