Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete an exact element in a bash array?

Tags:

arrays

bash

unset

I am trying to remove just the first appearance of any one keyword from a bash array.

ARRAY=(foo bar and any number of keywords)
keywords=(red, rednet, rd3.0)

I remove the keyword like this: ARRAY=( ${ARRAY[@]/"$keyword"/} ) then if "red' is the first found keyword, it will strip 'red' from both keywords and return "foo bar net" instead of "foo bar rednet".

Edit: Here is example, hopefully this makes it clearer.

for keyword in ${ARRAY[@]}; do
      if [ "$keyword" = "red" ] || [ "$keyword" = "rd3.0" ] || [ "$keyword" = "rednet" ]; then
           # HERE IS TROUBLE
           ARRAY=( ${ARRAY[@]/"$keyword"/} )
           echo "ARRAY is now ${ARRAY[@]}"
           break
      fi
 done

Which if the ARRAY=(red rednet rd3.0) returns net rd3.0 instead of rednet rd3.0

If I use unset,: unset ${ARRAY["$keyword"]} bash complains if the rd3.0 is in the array: :syntax error: invalid arithmetic operator (error token is ".0") What is the safe way to unset or remove just an exact match from an array?

like image 992
mateor Avatar asked Jan 10 '13 20:01

mateor


1 Answers

Use the unset command with the array value at index, something like this:

#!/usr/bin/env bash
ARRAY=(foo bar any red alpha number of keywords rd3.0 and)
keywords=(red, rednet, rd3.0)

index=0
for keyword in ${ARRAY[@]}; do
      if [ "$keyword" = "red" ] || [ "$keyword" = "rd3.0" ] || [ "$keyword" = "rednet" ]; then
           # HERE IS TROUBLE
           # ARRAY=( ${ARRAY[@]/"$p"/} )
           unset ARRAY[$index]
           echo "ARRAY is now: ${ARRAY[@]}"
           break
      fi
      let index++
 done
like image 110
higuaro Avatar answered Sep 19 '22 18:09

higuaro