0

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.

Paul
  • 442
  • 4
  • 9

2 Answers2

3

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)
Socowi
  • 25,550
  • 3
  • 32
  • 54
  • This is a great answer that also made it clear the difference between elements and indicies in a bash array. Thanks – hmedia1 Oct 26 '21 at 00:52
0

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
anubhava
  • 761,203
  • 64
  • 569
  • 643