问题
Ive look over many threads and cannot seem to put together a solution to my problem.
What i would like to do is use two lists to create one output.
set Client_ID=BJCH,BORG,FGMS,SVIN,JEFF,NWIL
set PartNo=1,2,9,10,12,20
for %%A in (%Client_ID%) do (
for %%B in (%PartNo%) do (
echo %%A %%B
)
)
But the output I get is:
BJCH 1
BJCH 2
BJCH 9
BJCH 10
BJCH 12
BJCH 20
BORG 1
BORG 2
BORG 9
BORG 10
BORG 12
BORG 20
FGMS 1
FGMS 2
FGMS 9
etc........
What i need is
BJCH 1
BORG 2
FGMS 9
SVIN 10
JEFF 12
NWIL 20
Any idea what I'm doing wrong? Any help is much appreciated.
回答1:
Your two lists are separated ones: if you nest one for
into the other one, you are multiplying the number of results. There is no way to process both lists in the same for
, unless you convert the lists into two arrays and then process both arrays in the same for
, that is, process the elements of the two arrays with same index. For example:
setlocal EnableDelayedExpansion
set Client_ID[1]=BJCH
set Client_ID[2]=BORG
etc...
set PartNo[1]=1
set PartNo[2]=2
etc...
for /L %%i in (1,1,6) do echo !Client_ID[%%i]! !PartNo[%%i]!
You may also simulate previous processing ("two elements with same index") this way:
@echo off
setlocal EnableDelayedExpansion
set Client_ID=BJCH,BORG,FGMS,SVIN,JEFF,NWIL
set PartNo=1,2,9,10,12,20
set i=0
for %%A in (%Client_ID%) do (
set /A i+=1, j=0
for %%B in (%PartNo%) do (
set /A j+=1
if !i! equ !j! echo %%A %%B
)
)
EDIT: Output example added
BJCH 1
BORG 2
FGMS 9
SVIN 10
JEFF 12
NWIL 20
来源:https://stackoverflow.com/questions/23258034/nested-for-loop-in-batch