How to delete an exact element in a bash array?

mateor picture mateor · Jan 10, 2013 · Viewed 9.3k times · Source

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?

Answer

higuaro picture higuaro · Jan 10, 2013

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