1

I have an array:

list[0]=.abc.com
list[1]=.dd.eu
list[3]=.ww.bb.com
list[4]=.abc.bgs.eu

i want to remove all items from array that ends with ".com"

Kriss
  • 435
  • 1
  • 10
  • 22

3 Answers3

2

You can do:

s='.com'
echo "${list[@]/*$s/}"
 .dd.eu  .abc.bgs.eu

Or else to store resulting array in a new array:

s='.com'
read -ra arr <<< "${list[@]/*$s/}"
declare -p arr
declare -a arr='([0]=".dd.eu" [1]=".abc.bgs.eu")'
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • this looks nice and fast : echo "${list[@]/*.com/}" but i need to pass variable to it. The ".com" part must be variable - how to do it ? echo "${list[@]/"$var"/}" does not work – Kriss Mar 25 '15 at 14:02
  • sure that can be done, see updated answer. – anubhava Mar 25 '15 at 14:03
  • 1
    `declare -p arr` is for printing the array content resulting from `read` call. What I've shown above is output of `declare -p arr` – anubhava Mar 25 '15 at 14:11
  • Does this approach work when there are spaces in the element strings? – Tom Fenech Mar 25 '15 at 14:13
  • Would need some tweaking but here OP is dealing with some domain names so space shouldn't be there IMO. – anubhava Mar 25 '15 at 14:15
1

Simple approach - make a new array containing the elements you're interested in keeping:

new_list=()
for i in "${list[@]}"; do [[ $i != *.com ]] && new_list+=( "$i" ); done
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
0

You can try this:

This stores array results in a different array.

declare -a pattern=( ${list[@]/*.com/} )
echo ${pattern[@]}

Here list is your array

list[0]=.abc.com
list[1]=.dd.eu
list[3]=.ww.bb.com
list[4]=.abc.bgs.eu

and pattern is the resulting array with the following output:

.dd.eu .abc.bgs.eu
Himanshu Chauhan
  • 812
  • 9
  • 11