dos 批处理迭代一个分隔的字符串 [英] dos batch iterate through a delimited string

查看:23
本文介绍了dos 批处理迭代一个分隔的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个分隔的 IP 列表,我想单独处理.列表长度提前未知.如何拆分和处理列表中的每个项目?

I have a delimited list of IPs I'd like to process individually. The list length is unknown ahead of time. How do I split and process each item in the list?

@echo off
set servers=127.0.0.1,192.168.0.1,10.100.0.1

FOR /f "tokens=* delims=," %%a IN ("%servers%") DO call :sub %%a

:sub
    echo In subroutine
    echo %1
exit /b

输出:

In subroutine
127.0.0.1
In subroutine
ECHO is off.

更新:使用 Franci 的回答作为参考,这是解决方案:

Update: Using Franci's answer as reference, here's the solution:

@echo off
set servers=127.0.0.1,192.168.0.1,10.100.0.1

call :parse "%servers%"
goto :end


:parse
setlocal
set list=%1
set list=%list:"=%
FOR /f "tokens=1* delims=," %%a IN ("%list%") DO (
  if not "%%a" == "" call :sub %%a
  if not "%%b" == "" call :parse "%%b"
)
endlocal
exit /b

:sub
setlocal
echo In subroutine
echo %1
endlocal
exit /b

:end

输出:

In subroutine
127.0.0.1
In subroutine
192.168.0.1
In subroutine
10.100.0.1

推荐答案

更新:如果列表中的项数未知,仍然可以通过简单的递归解析所有项列表的头部.(为简化列表,我已将 IP 更改为简单数字)

Update: If the number of items in the list is not known, it is still possible to parse all items with simple recursion on the head of the list. (I've changed the IPs to simple numbers for simplicity of the list)

我 18 年前上的 Lisp 课程终于得到了回报......

@echo off
setlocal

set servers=1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24

echo %servers%

call :parse "%servers%"

goto :eos

:parse

set list=%1
set list=%list:"=%

FOR /f "tokens=1* delims=," %%a IN ("%list%") DO (
  if not "%%a" == "" call :sub %%a
  if not "%%b" == "" call :parse "%%b"
)

goto :eos

:sub

echo %1

goto :eos

:eos
endlocal

这篇关于dos 批处理迭代一个分隔的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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