如何遍历逗号分隔字符串中的批次? [英] How to loop through comma separated string in batch?
问题描述
视窗
根据帖子( DOS批处理迭代>),我写了以下脚本,但不按预期工作。
目标:给定的字符串孙,花岗岩,暮光之城,我想在循环每个主题值,这样我可以用值做一些处理。
。电流输出是不是CORRCT:
列表=太阳,花岗岩,暮光之城
文件名是太阳花岗岩暮光之城
有关的第一次迭代应该是:
列表=太阳,花岗岩,暮光之城
文件名是太阳
然后第二次迭代应为文件名是花岗岩等。
我在做什么错了?
code:
集主题=太阳,花岗岩,暮光之城拨打:解析主题%%
转到:结束:解析
SETLOCAL
集列表=%1
回声列表=%列表%
FOR / Fdelims =,在(%目录%)做%% F(
REM如果项目存在
如果不是%% F==电话:getLineNumber %%˚F
REM若下一个项目存在
如果不是%% G==电话:解析%% G
)
ENDLOCAL:getLineNumber
SETLOCAL
回声文件名是1%
设置文件名=%1
ENDLOCAL:结束
我做了一些简单修改code。
- 需要转到:EOF在子程序结束,并在主程序的结束,这样你就不会落入子程序
- 标记= 1 *(%% f是第一个记号; %% g是该行的其余部分)
-
在〜集列表=%〜1去掉引号这样的报价不积累
关闭@echo
集主题=太阳,花岗岩,暮光之城拨打:解析主题%%
暂停
GOTO:EOF:解析
SETLOCAL
集列表=%〜1
回声列表=%列表%
FOR / F令牌= 1 * delims =%% f由于(%目录%)做(
REM如果项目存在
如果不是%% F==电话:getLineNumber %%˚F
REM若下一个项目存在
如果不是%% G==电话:解析%% G
)
ENDLOCAL
GOTO:EOF:getLineNumber
SETLOCAL
回声文件名是1%
设置文件名=%1
GOTO:EOF
Windows
Based on the post (dos batch iterate through a delimited string), I wrote a script below but not working as expected.
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.
Current output is not corrct:
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?
Code:
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.
- 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
这篇关于如何遍历逗号分隔字符串中的批次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!