Bash:计算关联数组中键的总数吗? [英] Bash: Count total number of keys in an associative array?

查看:86
本文介绍了Bash:计算关联数组中键的总数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的关联数组:

declare -A shapingTimes
 shapingTimes=([0-start]=15 [0-stop]=21 [0-anotherkey]=foo)
shapingTimes+=([1-start]=4  [1-stop]=6  [1-anotherkey]=bar)
shapingTimes+=([2-start]=9  [2-stop]=11 [2-anotherkey]=blah)

是否可以找到数组中每个条目使用的键总数?(这是数组中的每个索引"吗?)

Is there a way to find the total number of keys used per entry in an array? (Is this per 'index' in an array?)

例如,如何计算:[开始],[停止],[另一个键] = 3个键?

For example, how to count: [start], [stop], [anotherkey] as = 3 keys?

此刻,我正在使用此代码中的硬编码值(3)(如下所示)可以完成这项工作,但我想知道是否可以动态实现?

At the moment I'm using the hardcoded value (3) from this code I found (as below) that does the job fine, but I'm wondering if this can be achieved dynamically?

totalshapingTimes=$((${#shapingTimes[*]} / 3))

我发现这些变量可以返回数组的各个方面,但不能返回键的总数.

I've found these variables that return various array aspects, but not the total number of keys.

echo "All of the items in the array:" ${shapingTimes[*]}
echo "All of the indexes in the array:" ${!shapingTimes[*]}
echo "Total number of items in the array:" ${#shapingTimes[*]}
echo "Total number of KEYS in each array entry:" #???

所需的输出:

All of the items in the array: 21 6 11 blah 15 4 bar 9 foo
All of the indexes in the array: 0-stop 1-stop 2-stop 2-anotherkey 0-start 1-start 1-anotherkey 2-start 0-anotherkey
Total number of items in the array: 9
Total number of KEYS in each array entry: 3

推荐答案

declare -A shapingTimes
shapingTimes=([0-start]=15 [0-stop]=21 [0-anotherkey]=foo)
shapingTimes+=([1-start]=4  [1-stop]=6  [1-anotherkey]=bar)
shapingTimes+=([2-start]=9  [2-stop]=11 [2-anotherkey]=blah)

# output all keys
for i in "${!shapingTimes[@]}"; do echo $i; done

输出:


1-start
2-stop
1-stop
0-start
2-start
2-anotherkey
1-anotherkey
0-stop
0-anotherkey


# Leading numbers and "-" removed:
for i in "${!shapingTimes[@]}"; do echo ${i/#[0-9]*-/}; done

输出:


start
stop
stop
start
start
anotherkey
anotherkey
stop
anotherkey


# put shortend keys in new associative array
declare -A hash
for i in "${!shapingTimes[@]}"; do hash[${i/#[0-9]*-/}]=""; done
echo "${#hash[@]}"

输出:


3

这篇关于Bash:计算关联数组中键的总数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆