0

I have an array which i want to create a new array based on that, which contains just my particular selected items by index number.

for example i want to have an array which contains just two and five or with index number [2,4]

do you have an idea how to do it with bash script. i am new in bash thanks

array1=( one two three four five )
echo ${array1[@]}

result

array2 = (two five)

2 Answers 2

2

As far as I'm aware, the only way that you can do this is by making a new array, picking each element one by one:

array2=( "${array1[1]}" "${array1[4}}" ) # two five

If on the other hand you wanted a slice (consecutive indices), you could use the built-in syntax:

array2=( "${array1[@]:1:3}" ) # two three four
Sign up to request clarification or add additional context in comments.

Comments

0

You would need a loop:

indices=(1 3)
for i in "${indices[@]}"; do  # or for i in 1 3, if you want to hard-code the indices
  array2+=("${array[i]}")
done

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.