考虑下面的关联数组:
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)
有没有办法找到数组中每个条目使用的键总数? (这是数组中的每个“索引”吗?)
例如,如何计算:[start]、[stop]、[anotherkey] = 3 个键?
目前,我正在使用此代码中的硬编码值 (3),我发现(如下所示)可以很好地完成工作,但我想知道这是否可以动态实现?
totalshapingTimes=$((${#shapingTimes[*]} / 3))
我发现这些变量返回各个数组方面,但不是返回数组的总数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
Output:
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
Output:
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[@]}"
Output:
3
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)