views:

42

answers:

2

Hi,

I want to do sth. like this:

foo=(a b c)
foo-=b
echo $foo # should output "a c"

How can I remove an entry from an array? foo-=b does not work.

The removal should work no matter where the entry is.

A: 

foo = (1 2 3)

shift foo

print $foo gives: 2 3

So this removes the first element (is that what you want?)

[edited]

remove the ith element with

foo[$i] =()

instead.

Henno Brandsma
This only works if the entry is at index 0.
Albert
No, I want to remove the entry whereever it is (it is not always at the beginning).
Albert
What is `$i`? How do I get it?
Albert
@Albert: `foo(2)=()`
Dennis Williamson
@Dennis: You mean `$i=b`? That doesn't work. `foo(b)=()` is not valid.
Albert
@Albert: No I mean `i=2`, which is what the last option in this answer is intended to do. However, it's not what you're looking for.
Dennis Williamson
+3  A: 

To remove element number $i: a=("${(@)a[1,$i-1]}" "${(@)a[$i+1,$#a]}")

(The simpler construct a=($a[1,$i-1] $a[$i+1,$#a]) also removes empty elements.)

ADDED:

To remove any occurence of b: a=("${(@)a:#b}")
:# is the hieroglyph to remove matching elements; "" and (@) is to operate correctly on arrays even if they contain empty elements.

Gilles
This looks quite complicated. Also, how do I get `$i`? I just want to remove `b`.
Albert
@Albert: I've added how to remove by content.
Gilles
Thanks, that addition is exactly what I wanted.
Albert