arrays - 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.
解决方案
如果获取索引只是获取条目的一步,那么有一个简单的解决方案:将数组转换为密集(=非稀疏)数组,然后访问这些条目……</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)
推荐阅读
- c - 如何使用 scanf 函数从 ls -l 的结果中解析两个特定信息作为参数?
- javascript - 两步登录 - 第二步的问题
- angular - 我可以在不立即呈现更改的情况下更新 Firestore 文档吗?
- binary-tree - 重建一棵二叉树需要多少树旅行?
- javascript - 我想要输入的值,但它总是警告 0
- arrays - fortran 中的 array(2:)(::2) 有什么问题?
- c++ - 在 LLVM JIT-ed 代码中启用 RTTI 的问题
- html - 不可见时滚动到底部
- mysql - 无法将 mysql docker 容器与 Spring Boot 应用程序链接 - 通信链接失败
- selenium - 在 Robot Framework 中删除和添加数字的千位分隔符