4

I have an array tokens which contains tokens=( first one two three last ). How do I obtain the values ( one two three ) if I do not know how many numbers are in the array? I want to access everything between first and last (exclusive).

echo ${tokens[*]:1:3}

will give one two three but if I do not know the length of the array how can I get all the elements after first and before last? I am looking for something similar to using negative indices in Python such as tokens[1:-1]

Toby Speight
  • 8,460
  • 3
  • 26
  • 50
sriganesh
  • 101
  • 1
  • 6

2 Answers2

4

If the array is not sparse, you can do:

bash-5.2$ tokens=( {1..10} )
bash-5.2$ printf ' - %s\n' "${tokens[@]:1:${#tokens[@]}-2}"
 - 2
 - 3
 - 4
 - 5
 - 6
 - 7
 - 8
 - 9

If the array may be sparse, you'd need to determine the index of the second element (here assuming it has at least 2 elements):

bash-5.2$ tokens=([12]=a [15]=b [23]=c [123]=d)
bash-5.2$ ind=( "${!tokens[@]}" )
bash-5.2$ printf ' - %s\n' "${tokens[@]:ind[1]:${#tokens[@]}-2}"
 - b
 - c

In zsh (which has normal arrays, not sparse arrays), it's just $tokens[2,-2].

Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
3

Depending on your version of Bash, the following should work:

tokens=( first one two three last )
echo "${tokens[@]:1:${#tokens[@]}-2}"

Result

one two three
AdminBee
  • 21,637
  • 21
  • 47
  • 71