如何批量循环逗号分隔的字符串? [英] How to loop through comma separated string in batch?

查看:39
本文介绍了如何批量循环逗号分隔的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

视窗

基于帖子(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.

  1. 需要在子例程结束和主例程结束时使用 goto :eof 以免陷入子例程.
  2. tokens=1*(%%f 是第一个标记;%%g 是该行的其余部分)
  3. ~ in set list=%~1 删除引号,这样引号就不会累积

  1. Need goto :eof at end of subroutines and at end of main routine so you don't fall into subroutines.
  2. tokens=1* (%%f is first token; %%g is rest of the line)
  3. ~ 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆