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[@]}.
And repeat with other row indexes, if needed. The regular expression is a bit tricky.
\<is a beginning of word (to avoid that10,10matches0,).$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
-Eooptions of grep put it in extended regular expression mode and separate the matching strings with new lines, such thatwc -lcan count them.