删除确切的bash数组元素? [英] delete exact bash array element?

查看:143
本文介绍了删除确切的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 [@] /$关键字/})那么,如果红是第一个被发现的关键字,这将剥夺'的红色从两个关键字,并返回富巴网,而不是富红网吧。

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

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