arrays - Bash:计算关联数组中键的总数?

标签 arrays bash associative-array

考虑下面的关联数组:

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))
我发现这些变量返回数组的各个方面,但不是键的总数。
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

关于arrays - Bash:计算关联数组中键的总数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63532910/

相关文章:

windows - Cygwin 命令可从命令行运行,但不能从脚本运行

arrays - grep -B 模拟环形缓冲区/awk

arrays - 在 BASH 中对另一个数组进行迭代期间使用变量动态命名数组

php - array_diff() 基于具有关联行的两个数组之间的一列

javascript - 获取对象数组并按字母顺序排序为更小的数组

java - stat 返回 `No such file or directory` ,在 java exec 下运行

c - 2D Array 打印出符号

php - 使用 WordPress 发布元数据函​​数的 HTML 表单中的关联数组

javascript - 从 Three.js 中的 BufferGeometry 中删除顶点及其属性

php - in_array() 总是返回 TRUE