如何删除bash数组中的确切元素? [英] How to delete an exact element in a bash array?

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

问题描述

我正在尝试从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[@]/"$keyword"/} ),如果"red"是第一个找到的关键字,它将从两个关键字中删除" red ",并返回"foo bar net"而不是"foo bar rednet".

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=(red rednet rd3.0)返回 net rd3.0 而不是 rednet rd3.0

如果我使用unset,则:unset ${ARRAY["$keyword"]} bash抱怨rd3.0是否在数组中::syntax error: invalid arithmetic operator (error token is ".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?

推荐答案

使用unset命令并将数组值设置为index,如下所示:

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屋!

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