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]

2 Answers 2

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].

2
  • The key point being that Bash supports this simple arithmetic in its array indices, which was probably not known to sriganesh. Commented Oct 13, 2022 at 16:36
  • @TobySpeight, true though if it didn't support it, you could always do: "${tokens[@]:1:$(( ${#tokens[@]}-2 ))}" Commented Oct 13, 2022 at 16:38
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

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.