delete exact bash array element?

2019-03-30 10:10发布

问题:

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?

回答1:

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


回答2:

First: You should use quotation marks around your keys in the arrays. This avoids problems with for example rd3.0.

Like that:

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

In my opinion you need to copy the array and then use a for loop to filter the keywords. Exit the for loop after the first successful filtering. After that copy it back without the empty array elements. See this short examples (paragraph 10).

More on arrays: http://tldp.org/LDP/abs/html/arrays.html (everything you will ever need)