arraysbashunixmultidimensional-arraybash4

Getting length of part of associative array (double) in Bash


I have an associative array that acts like it's usual double array.

Structure is similar to this: [ [0,1], [0,1,2] ]. Code:

declare -A array
array[0,0]=0
array[0,1]=1
array[1,0]=0
array[1,1]=1
array[1,2]=2

How do I get lengths of array[0] and array[1]? In this example: 2 and 3.

Thank you.

P.S. I tried to search for duplicates. No success. And if it's not clear: I don't know the length of array.


Answer was chosen after efficiency testing. Here is example of function based on @RenaudPacalet's answer:

function getLength() {
    local k=$(eval "echo \${!$1[@]}")
    local re="(\<$2,[0-9])"
    echo $k | grep -Eo $re | wc -l
}

Usage example: getLength array 1 returns 3 in this question's case.

Keep in mind that using $(eval "echo \${!$1[@]}") is much slower than ${!array[@]}.


Solution

  • k=${!array[@]}
    n=0
    re="(\<$n,[0-9]+)"
    echo $k | grep -Eo $re | wc -l
    
    1. get the keys of your array,
    2. set the row index,
    3. create a regular expression for the matching keys,
    4. filter the keys using the regular expression and count the number of matches.

    And repeat with other row indexes, if needed. The regular expression is a bit tricky. \< is a beginning of word (to avoid that 10,10 matches 0,). $n,[0-9]+ is the current row index, followed by a comma and one or more digits. The enclosing parentheses delimit a sub-expression.

    The -Eo options of grep put it in extended regular expression mode and separate the matching strings with new lines, such that wc -l can count them.