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"

0

3 Answers 3

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")'
Sign up to request clarification or add additional context in comments.

5 Comments

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
sure that can be done, see updated answer.
declare -p arr is for printing the array content resulting from read call. What I've shown above is output of declare -p arr
Does this approach work when there are spaces in the element strings?
Would need some tweaking but here OP is dealing with some domain names so space shouldn't be there IMO.
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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.