Search code examples
bashassociative-array

Looping over associative array groups


I have an associative array asc with its keys in the following form

asc[1-0]=dlc[0]
asc[2-1]=dlc[1]
asc[3-2]=dlc[2]
asc[1-3]=dlc[3]
asc[2-4]=dlc[4]
asc[3-5]=dlc[5]
asc[1-6]=dlc[6]
asc[2-7]=dlc[7]
asc[3-8]=dlc[8]
asc[1-9]=dlc[9]
asc[2-10]=dlc[10]
asc[3-11]=dlc[11]
asc[1-12]=dlc[12]
asc[2-13]=dlc[13]

...

I would like to group the elements by the first number when I call a function fn.

loop over i
  fn asc[i-*]  $ pass all elements with i as first number

Solution

  • You'll have to iterate over the keys of the associative array and build up an ordinary array of the values associated with the desired subset of keys.

    for i in 1 2 3; do
        group=()
        for k in "${!asc[@]}"; do
            [[ $k = $i-* ]] || continue
            group+=("${asc[$k]}")
        done
        fn "${group[@]}"
    done