Array - Remove elements from a linux shell array
In this article we can learn how to delete/remove elements/indexes from an linux bash shell array.
The following way can remove an array element completely:
1 arr=(eth eos btc usd etc)
2 delete=2
3 arr=( "${arr[@]:0:$delete}" "${arr[@]:$(($delete+1))}" )
4 echo "${arr[@]}"
Print array without removing a array element:
1 arr=(eth usd btc);
2 echo "${arr[@]/usd}";
Remove a array element using element name:
1 arr=(eth usd btc);
2 arr=( "${arr[@]/usd}" );
3 echo "${arr[@]}"
Remove a element name using index value in bash:
1 arr=(eth usd btc);
2 unset arr[1];
3 echo "${arr[@]}"
Remove first and last element from an array in bash:
1 arr=(eth btc usd eos);
2 unset 'arr[0]'
3 unset 'arr[-1]'
4 echo "${#arr[*]}"
Remove multiple elements from an array using element names:
1 arr=(eth usd btc etc)
2 delete=(etc eth)
3 for current in "${delete[@]}"
4 do
5 arr=( "${arr[@]/$current}" )
6 done
7 echo -e "${arr[@]}"
Remove multiple elements from arrays using element values in bash:
1 arr=(eth usd btc etc)
2 arr2=(210 1 9417 8)
3 unset arr[0] arr[3] arr2[0] arr2[3]
4 echo -e "${arr[@]}
5 ${arr2[@]}"
Or remove elements one by one in bash shell:
1 arr=(eth usd btc etc)
2 delete=(0 3)
3 for value in "${delete[@]}"
4 do
5 unset arr[$value]
6 done
7 echo "${arr[@]}"