【发布时间】:2019-12-06 03:45:42
【问题描述】:
我正在尝试编写一个从数组中删除值的函数按值。不,我不想按索引删除它。
这是我迄今为止尝试过的。
我见过函数之外的例子。我不得不做一些奇怪的shift 事情来传递参数,最终找到第一个变量,而不是遍历其余变量,仍然能够传递数组。
# Create the array.
LIST=()
LIST+=("one")
LIST+=("two")
LIST+=("three")
# List all the items.
for item in "${LIST[@]}"
do
echo ITEM: $item
done
# Try to define the remove function.
array_remove()
{
FIND=$1 # I'm looking for the first argument.
echo FIND: $FIND
DELETE=($1) # I want to delete this, I've been told to make this also an array....
shift # I have to "shift" to make the rest work.
ARRAY=("$@") # This is the actual second parameter.
for target in "${ARRAY[@]}"; do
for i in "${!ARRAY[@]}"; do
if [[ ${ARRAY[i]} = "${DELETE[0]}" ]]; then
unset 'ARRAY[i]'
fi
done
done
# Now at this point $ARRAY is actually correct, but I want to change $LIST.
"$@"=$ARRAY # How???
}
# Try to remove "two" from the $LIST
array_remove "two" "${LIST[@]}"
# List all the items again, make sure they're removed.
for item in "${LIST[@]}"
do
echo ITEM AGAIN: $item
done
这行不通。我已经尝试了很多东西。我从根本上不了解 bash 的工作原理,而且它非常不稳定,与我所知道的任何编程语言不同(我知道一些)。
上面给了我这个。
ITEM: one
ITEM: two
ITEM: three
FIND: two
array.sh: line 25: one: command not found
ITEM AGAIN: one
ITEM AGAIN: two
ITEM AGAIN: three
【问题讨论】:
-
您的问题似乎与此处回答的问题非常相似 stackoverflow.com/a/16861932/4087040
-
看起来确实很相似,但不在函数中
-
只是为了确定。请确认:您需要一个带有字符串和数组名称(!)的函数(目前,您传递的是数组条目,而不是数组名称)。该函数应从数组中删除与给定字符串匹配的所有条目。数组应该被修改。
-
"函数应该从数组中删除所有匹配给定字符串的条目。数组应该被修改。"是的