Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove entry from array

Tags:

arrays

shell

zsh

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.

like image 482
Albert Avatar asked Aug 08 '10 17:08

Albert


2 Answers

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,-1]) 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.

like image 58
Gilles 'SO- stop being evil' Avatar answered Sep 18 '22 22:09

Gilles 'SO- stop being evil'


Gilles second answer is correct if you wish to remove all occurences, but it is a full reassignment of the array and does not address the situation where you wish to remove only a single entry, regardless of duplicates. There is a way in zsh to remove an element from an normal array without reassigning the entire array:

Given the following array:

array=(abc def ghi) 

the following will return the index of the first match for def:

${array[(i)def]} 

and the following format can be used to remove any given indexed value (element index 2 in this example) in an array without reassignment of the entire array:

array[2]=() 

thus, to remove the value def we combine the two:

array[$array[(i)def]]=() 

This is cleaner for single element removal, since there is no explicit array reassignment (cleaner in that any potential side effects, such as the accidental removal of empty items, quoted format issues, etc. are not going to crop up). However Gilles' solution is largely equivalent and has the advantage of multiple matching item removal, if that is what you want. With his method and this method, you have a full toolset for standard array element removal.

like image 20
altercation Avatar answered Sep 20 '22 22:09

altercation