First let me state my problem clearly:
Ex: Let's pretend this is my array, (the elements don't matter as in my actual code they vary):
array=(jim 0 26 chris billy 78 hello foo bar)
Now say I want to remove the following elements:
chris 78 hello
So I did: unset array[$i]
while looping through the array.
This removes the elements correctly, however, i end up with an array that looks like this:
array=(jim 0 26 '' billy '' '' foo bar)
I need it to look like this:
array=(jim 0 26 billy foo bar)
where jim is at index 0, 0@1, 26@2, etc..
How do I delete the elements in the array and move the other elements so that there are no null/empty spaces in the array?
Thanks!
To remove an array element at index i, you shift elements with index greater than i left (or down) by one element. For example, if you want to remove element 3, you copy element 4 to element 3, element 5 to element 4, element 6 to element 5.
pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.
To really remove an exact item, you need to walk through the array, comparing the target to each element, and using unset to delete an exact match. Note that if you do this, and one or more elements is removed, the indices will no longer be a continuous sequence of integers.
Pass the value of the element you wish to remove from your array into the indexOf() method to return the index of the element that matches that value in the array. Then make use of the splice() method to remove the element at the returned index.
Try this:
$ array=( "one two" "three four" "five six" )
$ unset array[1]
$ array=( "${array[@]}" )
$ echo ${array[0]}
one two
$ echo ${array[1]}
five six
Shell arrays aren't really intended as data structures that you can add and remove items from (they are mainly intended to provide a second level of quoting for situations like
arr=( "one two" "three four" )
somecommand "${arr[@]}"
to provide somecommand
with two, not four, arguments). But this should work in most situations.
See http://www.thegeekstuff.com/2010/06/bash-array-tutorial
...
Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
pos=3
Unix=(${Unix[@]:0:$pos} ${Unix[@]:$(($pos + 1))})
This contracts the array around pos, which the original poster wanted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With