Reputation: 582
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.
Upvotes: 0
Views: 299
Reputation: 27370
If getting the index is only a step towards getting the entry then there is an easy solution: Convert the array into a dense (= non-sparse) array, then access those entries …
sparse=([1]=I [5]=V [10]=X [50]=L)
dense=("${sparse[@]}")
printf %s "${dense[2]}"
# prints X
Or as a function …
nthEntry() {
shift "$1"
shift
printf %s "$1"
}
nthEntry 2 "${sparse[@]}"
# prints X
Assuming (just like you did) that the list of keys "${!sparse[@]}"
expands in sorted order (I found neither guarantees nor warnings in bash's manual, therefore I opened another question) this approach can also be used to extract the nth index without external programs like cut
.
indices=("${!sparse[@]}")
echo "${indices[2]}"
# prints 10 (the index of X)
nthEntry 2 "${!sparse[@]}"
# prints 10 (the index of X)
Upvotes: 3
Reputation: 786359
If I understood your question correctly, you may use it like this using read
:
# sparse array
declare -a arr=([10]="10" [15]="20" [21]="30" [34]="40" [47]="50")
# desired index
n=2
# read all indices into an array
read -ra iarr < <(printf "%s\t" ${!arr[@]})
# fine nth element
echo "${arr[${iarr[n]}]}"
30
Upvotes: 0