14

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!

4 Answers 4

27

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Sorry I am a bit late in marking this as correct. It helped me out. thanks.
4

See http://www.thegeekstuff.com/2010/06/bash-array-tutorial

  1. Remove an Element from an Array

...

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.

Comments

0

Try this:

user@pc:~$ array=(jim 0 26 chris billy 78 hello foo bar)
user@pc:~$ for itm2rm in chris 78 hello; do array=(\`echo ${array[@]} | sed "s/\<${itm2rm}\>//g"\`); done ; echo ${array[@]}
jim 0 26 billy foo bar

Comments

0

this post had been revised and moved to its own post as a more in-depth tutorial how to remove an array element correctly in a for loop

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.