Windows 循环遍历变量值的批处理

Windows batch to loop through values for variable

我有主要的价值观和它的一个子集

主集:Group1,Group2,Group3

子集:Group1_Sub1,Group1_Sub2,Group2_Sub1,Group3_Sub1,Group3_Sub2

Group1 ->Group1_Sub1 and Group1_Sub2

Group2 ->Group2_Sub1

Group3 ->Group3_Sub1,Group3_Sub2

对于每个主列表,我只想循环遍历其对应的子组列表并显示输出。

目前我正在使用下面的代码

for %%s in (

Group1,Group2,Group3

    ) do (

        echo set Main Group %%s >> Log.txt

        for %%i in (
                    Group1_Sub1,Group1_Sub2,Group2_Sub1,Group3_Sub1,Group3_Sub2
                    ) do (
                        echo Main Group is %%s and its sub group is %%i >>Log.txt
                         )
            )

上面的代码将给我输出:

set Main Group Group1 
Main Grpup is Group1 and its sub group is Group1_Sub1 
Main Grpup is Group1 and its sub group is Group1_Sub2 
Main Grpup is Group1 and its sub group is Group2_Sub1 
Main Grpup is Group1 and its sub group is Group3_Sub1 
Main Grpup is Group1 and its sub group is Group3_Sub2 
set Main Group Group2 
Main Grpup is Group2 and its sub group is Group1_Sub1 
Main Grpup is Group2 and its sub group is Group1_Sub2 
Main Grpup is Group2 and its sub group is Group2_Sub1 
Main Grpup is Group2 and its sub group is Group3_Sub1 
Main Grpup is Group2 and its sub group is Group3_Sub2 
set Main Group Group3 
Main Grpup is Group3 and its sub group is Group1_Sub1 
Main Grpup is Group3 and its sub group is Group1_Sub2 
Main Grpup is Group3 and its sub group is Group2_Sub1 
Main Grpup is Group3 and its sub group is Group3_Sub1 
Main Grpup is Group3 and its sub group is Group3_Sub2 

我想限制他们只浏览下面相应的列表

set Main Group Group1 
Main Grpup is Group1 and its sub group is Group1_Sub1 
Main Grpup is Group1 and its sub group is Group1_Sub2 
set Main Group Group2 
Main Grpup is Group2 and its sub group is Group2_Sub1 
set Main Group Group3  
Main Grpup is Group3 and its sub group is Group3_Sub1 
Main Grpup is Group3 and its sub group is Group3_Sub2 

我怎样才能做到这一点?

在内 (%%i) 循环内:

    ECHO %%i|FINDSTR /b /i /L /c:"%%s_">nul
    IF NOT ERRORLEVEL 1 echo Main Group is %%s and its sub group is %%i >>Log.txt

Group1_Sub2 回显(例如)到 findstr 中,后者查找以 %%s 的当前值 + 下划线开头的字符串 /b/i表示case-insensitive,/L表示文字比较,/c:表示要检测的字符串。

如果 findstr 找到了它正在寻找的字符串,那么 errorlevel 将被设置为 0 或 1,否则。 >nul 抑制输出。 errorlevel 然后可以使用常规语法进行测试。

正如您所说的变量:以下代码自行查找主要组及其子组:

@echo off
setlocal enabledelayedexpansion

REM following line just for generating test variables:
for %%a in (1 2 3) do for %%b in (1 2 3 4) do set "Group%%a_Sub%%b=!random!"

REM search MainGroups:
for /f "delims=_" %%a in ('set group') do set "Main_%%a=Group"
REM process each MainGroup
for /f "tokens=2 delims=_=" %%a in ('set Main_') do (
  echo set Main Group %%a
  for /f "delims==" %%b in ('set %%a_') do (
    echo Main Group is %%a and its sub group is %%b and its content is !%%b!
  )
)

优点:无需对每个变量名称进行硬编码
Con (?): 不列出空 (non-existing) 变量(根据您的需要,这甚至可能是另一个 Pro)