从 Bash 数组中删除一个元素 [英] Remove an element from a Bash array

查看:40
本文介绍了从 Bash 数组中删除一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从 bash shell 中的数组中删除一个元素.通常我会这样做:

I need to remove an element from an array in bash shell. Generally I'd simply do:

array=("${(@)array:#<element to remove>}")

不幸的是,我想删除的元素是一个变量,所以我不能使用前面的命令.下面是一个例子:

Unfortunately the element I want to remove is a variable so I can't use the previous command. Down here an example:

array+=(pluto)
array+=(pippo)
delete=(pluto)
array( ${array[@]/$delete} ) -> but clearly doesn't work because of {}

有什么想法吗?

推荐答案

以下在 bashzsh 中的工作方式:

The following works as you would like in bash and zsh:

$ array=(pluto pippo)
$ delete=pluto
$ echo ${array[@]/$delete}
pippo
$ array=( "${array[@]/$delete}" ) #Quotes when working with strings

如果需要删除多个元素:

If need to delete more than one element:

...
$ delete=(pluto pippo)
for del in ${delete[@]}
do
   array=("${array[@]/$del}") #Quotes when working with strings
done

警告

这种技术实际上是从元素中删除与 $delete 匹配的前缀,不一定是整个元素.

This technique actually removes prefixes matching $delete from the elements, not necessarily whole elements.

更新

要真正删除精确的项目,您需要遍历数组,将目标与每个元素进行比较,然后使用 unset 删除精确匹配项.

To really remove an exact item, you need to walk through the array, comparing the target to each element, and using unset to delete an exact match.

array=(pluto pippo bob)
delete=(pippo)
for target in "${delete[@]}"; do
  for i in "${!array[@]}"; do
    if [[ ${array[i]} = $target ]]; then
      unset 'array[i]'
    fi
  done
done

请注意,如果您这样做,并且删除了一个或多个元素,则索引将不再是连续的整数序列.

Note that if you do this, and one or more elements is removed, the indices will no longer be a continuous sequence of integers.

$ declare -p array
declare -a array=([0]="pluto" [2]="bob")

一个简单的事实是,数组不是为用作可变数据结构而设计的.它们主要用于在单个变量中存储项目列表,而无需浪费一个字符作为分隔符(例如,存储可以包含空格的字符串列表).

The simple fact is, arrays were not designed for use as mutable data structures. They are primarily used for storing lists of items in a single variable without needing to waste a character as a delimiter (e.g., to store a list of strings which can contain whitespace).

如果间隙是个问题,那么你需要重建数组来填补间隙:

If gaps are a problem, then you need to rebuild the array to fill the gaps:

for i in "${!array[@]}"; do
    new_array+=( "${array[i]}" )
done
array=("${new_array[@]}")
unset new_array

这篇关于从 Bash 数组中删除一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆