0

Team, I have a use case to save remainder of array into new array while looping on its indices and new array should have all elements except the looped element.

$ a=(1 2 3 4 5)
$ b=()

for index in ${!a[@]}
do
 b=(a - a[$index]) #how would i code his that it works ?
 echo ${b[@]}
done

expected loop values for each iteration.

1 2 3 4 
1 2 3 5
1 2 4 5
1 3 4 5
2 3 4 5
Barmar
  • 741,623
  • 53
  • 500
  • 612
AhmFM
  • 1,552
  • 3
  • 23
  • 53
  • See [BASH: deleting Nth element in an array without another variable](https://stackoverflow.com/q/71154323/4154375). – pjh Apr 20 '23 at 00:44

2 Answers2

2

Just be simple.

b=("${a[@]}")
unset b[$index]
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • See [Bash Pitfalls #57 (unset unquoted array element)](https://mywiki.wooledge.org/BashPitfalls#unset_a.5B0.5D). – pjh Apr 20 '23 at 00:38
0

Use the parameter expansion with the :offset:length syntax:

#!/bin/bash
a=(1 2 3 4 5)
b=()

for index in "${!a[@]}" ; do
    b=("${a[@]:0:index}")

    # This should be "${a[@]:index+1:${#a[@]}-index-1}",
    # but the result is the same.
    b+=("${a[@]:index+1:${#a[@]}}")

    echo "${b[@]}"
done
choroba
  • 231,213
  • 25
  • 204
  • 289