How to delete an exact element in a bash array?

南楼画角 提交于 2019-12-03 08:22:57

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

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)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!