【问题标题】:Bash, remove a value from an array (by value) (in a function)Bash,从数组中删除一个值(按值)(在函数中)
【发布时间】: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
  • 看起来确实很相似,但不在函数中
  • 只是为了确定。请确认:您需要一个带有字符串和数组名称(!)的函数(目前,您传递的是数组条目,而不是数组名称)。该函数应从数组中删除与给定字符串匹配的所有条目。数组应该被修改。
  • "函数应该从数组中删除所有匹配给定字符串的条目。数组应该被修改。"是的

标签: arrays bash


【解决方案1】:

这里唯一的困难是你必须将数组的名称(!)传递给你的函数和你的函数,以扩展一个名称存储在变量中的数组。为此你可以使用bash的indirection operator !

someArray=(first second third)
nameOfTheArray='someArray[@]'
echo "$nameOfTheArray"    # prints someArray[@]
echo "${!nameOfTheArray}" # prints first second third

现在我们可以将来自»Remove an element from a Bash array« 的任何解决方案与这个间接运算符结合起来。以下函数基于this answer——在我看来是最好的方法:

removeFromArray() {
    arrayName="$1"
    arrayNameAt="$arrayName"'[@]'
    removeValue="$2"
    mapfile -d '' -t "$arrayName" < <(
        printf %s\\0 "${!arrayNameAt}" | grep -zvFx "$removeValue")
}

如下使用这个函数。

a=(deleteMe test deleteMe something)
removeFromArray a deleteMe
echo "${a[@]}" # prints test something

【讨论】:

    猜你喜欢
    • 2012-02-11
    • 1970-01-01
    • 2015-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-19
    • 1970-01-01
    相关资源
    最近更新 更多