删除确切的bash数组元素? [英] delete exact bash array element?
问题描述
我想从一个bash数组中删除是任何一个关键字的首次亮相
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)
我删除关键字如下: ARRAY =($ {ARRAY [@] /$关键字/})
那么,如果红是第一个被发现的关键字,这将剥夺'的红色从两个关键字,并返回富巴网,而不是富红网吧。
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".
编辑:下面是例子,希望这使得它更清晰。
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
这要是 ARRAY =(红色红网rd3.0)
收益净rd3.0 而不是红网rd3.0
如果我使用未设置,: 未设置$ {ARRAY [$关键字]}
如果rd3.0是数组在bash抱怨::语法错误:无效的算术运算符(错误标记为.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?
推荐答案
在指数使用与阵列值
,是这样的:取消设置
命令
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
这篇关于删除确切的bash数组元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!