0

I am running multiple for loops over custom tool that produces array of result.

I need to flatten them into one collection without duplicates.

My first idea was to create array that keys are the items, see below. But this is nightmare to iterate afterwards...:

set apps=
for /d %%s in (".\manifests\*.xml") do (
    for /f "tokens=*" %%g in ('xml sel -t -v "\apps\app" %cd%\manifests\%%s') do (
            echo Found app - %%g [inside %%s]
            rem First idea below:
            set apps[%%g]=true
        )
)
rem How to iterate apps afterwards?
double-beep
  • 5,031
  • 17
  • 33
  • 41
PiotrK
  • 4,210
  • 6
  • 45
  • 65
  • 1
    To iterate apps: `for /F "tokens=2 delims=[]" %%a in ('set apps[') do echo %%a`. BTW the first `set apps=` command is not needed because the `apps` variable have no relation to the `apps[index]` ones. See: https://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990 – Aacini Dec 01 '18 at 18:31
  • @Aacini Can you post this as answer, so I can upvote it? – PiotrK Dec 03 '18 at 14:53
  • 1
    Done! You may also change the selected answer, if you wish... **`;)`** – Aacini Dec 03 '18 at 16:39

2 Answers2

1

Just nailed it:

set apps=
set apps_defined=

for /d %%s in (".\manifests\*.xml") do (
    for /f "tokens=*" %%g in ('xml sel -t -v "\apps\app" %cd%\manifests\%%s') do (
            echo Found app - %%g [inside %%s]

            if not "apps_defined[%%g]"=="true" (
                 if not "!apps!"=="" set apps=!apps!,
                 set apps=!apps!%%g
            )

            set apps_defined[%%g]=true
        )
)
PiotrK
  • 4,210
  • 6
  • 45
  • 65
  • 1
    Note that `apps_defined` is a _different variable_ than `apps_defined[1]`, so your initial `set apps_defined=` command is useless... I suggest you to read [this answer](https://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990). Also, it is simpler to use `if not defined apps_defined[%%g] (` instead of `if not "apps_defined[%%g]"=="true" (` – Aacini Dec 03 '18 at 16:44
1

Your idea to get elements without duplicates via an array is good. I only suggest you to enclose between quotes the variable=value part of set commands; this is a good practice to avoid unnoticed spaces that may be assigned to the variable.

After you created the array, you may iterate the elements in a very simple way:

@echo off
setlocal

for /d %%s in (".\manifests\*.xml") do (
    for /f "tokens=*" %%g in ('xml sel -t -v "\apps\app" %cd%\manifests\%%s') do (
            echo Found app - %%g [inside %%s]
            rem First idea below:
            set "apps[%%g]=true"
        )
)

rem Iterate the array elements:
for /F "tokens=2 delims=[]" %%a in ('set apps[') do echo %%a
Aacini
  • 65,180
  • 12
  • 72
  • 108