【问题标题】:Looping over Array's values in Batch批量循环数组的值
【发布时间】:2018-08-16 10:44:38
【问题描述】:

我有一个 File_2,其中包含以下行

A1,A2,A3,A4
B1,B2,B3,B4

在另一个 File_1 中,我有多行如下:

X
Y
Z

我想要的是拥有所有可能组合的 File_3:

A1;A2;X;A4
A1;A2;Y;A4
A1;A2;Z;A4
B1;B2;X;B4
B1;B2;Y;B4
B1;B2;Z;B4

我使用从 File_1 填充数组的代码,然后尝试将它与 File_2 结合以获得 File_3:

SET /A i=0
FOR /F "tokens=1" %%a IN (File_1.txt) DO (
    SET /P Var[%i%]=%%a
    SET /A i=+1
)

SET /A Counter=0

FOR /F "delims=, tokens=1-7" %%a IN (File_2.txt) DO (
    IF %Counter% LEQ %i% (
        ECHO %%a;%%b;%%Var[i]%%;%%d;>>File_3.txt
        SET /A Counter=+1
    )
)

第二个循环似乎不起作用。知道我的 Array 不是静态的,如何使用我的 Array 的值?

【问题讨论】:

  • %Counter%不更新,需要申请delayed expansion,所以使用!Counter!。但是为什么不使用for /L %%I in (1,1,%Counter%) do call echo %%a;%%b;%%Var[%%I]%%;%%d>>File_3.txt呢?

标签: arrays batch-file for-loop


【解决方案1】:

不需要数组;只有两个嵌套的for /f 循环:

@echo off
(for /f %%x in (file_1.txt) do (
  for /f "tokens=1-4 delims=," %%a in (file_2.txt) do (
    echo %%a;%%b;%%x;%%d
  )
))>file_3.txt

输出:

A1;A2;X;A4
B1;B2;X;B4
A1;A2;Y;A4
B1;B2;Y;B4
A1;A2;Z;A4
B1;B2;Z;B4

@echo off
(for /f "tokens=1-4 delims=," %%a in (file_2.txt) do (
  for /f %%x in (file_1.txt) do (
    echo %%a;%%b;%%x;%%d
  )
))>file_3.txt

输出:

A1;A2;X;A4
A1;A2;Y;A4
A1;A2;Z;A4
B1;B2;X;B4
B1;B2;Y;B4
B1;B2;Z;B4

取决于您希望它如何排序。

【讨论】:

    猜你喜欢
    • 2013-07-18
    • 2013-08-30
    • 1970-01-01
    • 2010-12-19
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多