MST
星途 面试题库

面试题:Bash关联数组的复杂嵌套与数据处理

假设你有一个复杂的Bash关联数组结构,其中包含多层嵌套的关联数组和普通数组。例如,外层关联数组的键是'group1','group2'等,对应的值又是一个关联数组,其键为'subgroup1','subgroup2'等,而这些子关联数组的值又是普通数组。现在需要编写一段Bash脚本,能够遍历这个复杂结构,统计出所有普通数组中元素的总数,并输出结果。
32.7万 热度难度
编程语言Bash

知识考点

AI 面试

面试题答案

一键面试
#!/bin/bash

# 定义复杂的关联数组结构
declare -A complex_array
complex_array=(
    ['group1']='([subgroup1]=([0]="value1" [1]="value2") [subgroup2]=([0]="value3"))'
    ['group2']='([subgroup1]=([0]="value4"))'
)

total_count=0

# 遍历外层关联数组
for outer_key in "${!complex_array[@]}"; do
    # 获取外层关联数组的值(子关联数组)
    inner_array=${complex_array[$outer_key]}
    # 遍历子关联数组
    for inner_key in "${!inner_array[@]}"; do
        # 获取子关联数组的值(普通数组)
        sub_array=${inner_array[$inner_key]}
        # 统计普通数组元素个数并累加到总数
        count=${#sub_array[@]}
        total_count=$((total_count + count))
    done
done

echo "所有普通数组中元素的总数: $total_count"