首页 > 解决方案 > Get the index of the first or nth element of sparse bash array

问题描述

Is there a bash way to get the index of the nth element of a sparse bash array?

printf "%s\t" ${!zArray[@]} | cut -f$N

Using cut to index the indexes of an array seems excessive, especially in reference to the first or last.

标签: arraysbashindexing

解决方案


如果获取索引只是获取条目的一步,那么有一个简单的解决方案:将数组转换为密集(=非稀疏)数组,然后访问这些条目……</p>

sparse=([1]=I [5]=V [10]=X [50]=L)
dense=("${sparse[@]}")
printf %s "${dense[2]}"
# prints X

或者作为一个函数……</p>

nthEntry() {
    shift "$1"
    shift
    printf %s "$1"
}
nthEntry 2 "${sparse[@]}"
# prints X

假设(就像你做的那样)键列表"${!sparse[@]}"按排序顺序扩展(我在bash 的手册中既没有发现保证也没有警告,因此我打开了另一个问题)这种方法也可以用于提取第 n 个索引,而无需像cut.

indices=("${!sparse[@]}")
echo "${indices[2]}"
# prints 10 (the index of X)

nthEntry 2 "${!sparse[@]}"
# prints 10 (the index of X)

推荐阅读