循环遍历数组的值

时间:2018-08-16 10:44:39

标签: arrays batch-file for-loop

我有一个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
    )
)

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

1 个答案:

答案 0 :(得分:2)

不需要数组;只有两个嵌套的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

取决于您希望的排序方式。