Jump to content

Nested Loops of Array Elements


Recommended Posts

Hey, can I do this in dos?

Used to do similar on Unix but can't see how to make it work for Windows.

-----

Set Pets=(Cats Dogs Horses)

Set Cats=(FiFi FruFru Fluffy)

Set Dogs=(Lassie MrMuggles RinTinTin)

Set Horsese=(MrEd Trigger)

FOR %%A in %Pets% DO (

FOR %%B in %%A DO (

Echo “%%A %%B”

)

)

-----

Output should be…

Cats FiFi

Cats FruFru

Cats Fluffy

Dogs Lassie

Dogs MrMuggles

Dogs RinTinTin

Horses MrEd

Horses Trigger

This obviously does not work, is there any way to achieve this?

Simon.

Link to comment
Share on other sites


I do not have a DOS system to test this on, only a Windows 7 command prompt (cmd.exe).

This will do for the specific conditions you have listed.

Changes will need to be made if any of the pet names will have spaces.

@echo off

Set Pets=Cats Dogs Horses
Set Cats=FiFi FruFru Fluffy
Set Dogs=Lassie MrMuggies RinTinTin
Set Horses=MrEd Trigger

For %%a In (%Pets%) Do (
For /f "Tokens=1,* delims== " %%b In ('set %%a') Do (
For %%n In (%%c) Do (
Echo %%a %%n
)
)
)

Link to comment
Share on other sites

If I may, if DELAYEDEXPANSION is set, you don't even need the FOR /F:

@ECHO OFF
SETLOCAL ENABLEEXTENSIONS
SETLOCAL ENABLEDELAYEDEXPANSION

Set Pets=Cats Dogs Horses
Set Cats=FiFi FruFru Fluffy
Set Dogs=Lassie MrMuggles RinTinTin
Set Horses=MrEd Trigger


For %%A In (%Pets%) Do (
For %%B In (!%%A!) Do (
For %%C In (%%B) Do (
Echo %%A %%C
)
)
)

jaclaz

Link to comment
Share on other sites

Here is a way of doing what the poster wants using VBS script.


Dim Pets :Pets = Array("Cats","Dogs","Horses")
Dim a,c,i,z
'-> Loop Threw Pets Array
For Each a In Pets
c = c + 1
call SortArray(a, c)
Next
'-> Function To Display Pets Array And Names
Function SortArray(Item, N)
Select Case N
Case 1 :i = Array("FiFi", "FruFru", "Fluffy")
Case 2 :i = Array("Lassie", "MrMuggles", "RinTinTin")
Case 3 :i = Array("MrEd", "Trigger", "Silver")
End Select
For Each z In i
WScript.Echo Item & vbTab & z
Next
End Function

Produces this output


Cats FiFi
Cats FruFru
Cats Fluffy
Dogs Lassie
Dogs MrMuggles
Dogs RinTinTin
Horses MrEd
Horses Trigger
Horses Silver

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...