bash 如何删除数组中的元素,然后在 Shell 脚本中移动数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17533231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:51:42  来源:igfitidea点击:

How can i delete an element in an array and then shift the array in Shell Script?

bashshell

提问by tc90

First let me state my problem clearly:

首先让我清楚地说明我的问题:

Ex: Let's pretend this is my array, (the elements don't matter as in my actual code they vary):

例如:让我们假设这是我的数组,(元素并不重要,因为在我的实际代码中它们会有所不同):

array=(jim 0 26 chris billy 78 hello foo bar)

Now say I want to remove the following elements:

现在说我想删除以下元素:

chris 78 hello

So I did: unset array[$i]while looping through the array. This removes the elements correctly, however, i end up with an array that looks like this:

所以我做了:unset array[$i]同时循环遍历数组。这将正确删除元素,但是,我最终得到一个如下所示的数组:

array=(jim 0 26 '' billy '' '' foo bar)

I need it to look like this:

我需要它看起来像这样:

array=(jim 0 26 billy foo bar)

where jimis at index 0, 0@1, 26@2, etc..

其中jim位于索引00@126@2等处。

How do I delete the elements in the array and move the other elements so that there are no null/empty spaces in the array?

如何删除数组中的元素并移动其他元素,以便数组中没有空/空白空间?

Thanks!

谢谢!

回答by chepner

Try this:

尝试这个:

$ array=( "one two" "three four" "five six" )
$ unset array[1]
$ array=( "${array[@]}" )
$ echo ${array[0]}
one two
$ echo ${array[1]}
five six

Shell arrays aren't really intended as data structures that you can add and remove items from (they are mainly intended to provide a second level of quoting for situations like

Shell 数组并不是真正用作可以从中添加和删除项目的数据结构(它们主要用于为以下情况提供第二级引用:

arr=( "one two" "three four" )
somecommand "${arr[@]}"

to provide somecommandwith two, not four, arguments). But this should work in most situations.

提供somecommand两个而不是四个参数)。但这应该适用于大多数情况。

回答by Alexey Pismenny

See http://www.thegeekstuff.com/2010/06/bash-array-tutorial

http://www.thegeekstuff.com/2010/06/bash-array-tutorial

  1. Remove an Element from an Array
  1. 从数组中删除元素

...

...

Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');

pos=3

Unix=(${Unix[@]:0:$pos} ${Unix[@]:$(($pos + 1))})

This contracts the array around pos, which the original poster wanted.

这会收缩 pos 周围的数组,这是原始发布者想要的。

回答by mark_infinite

Try this:

尝试这个:

user@pc:~$ array=(jim 0 26 chris billy 78 hello foo bar)
user@pc:~$ for itm2rm in chris 78 hello; do array=(\`echo ${array[@]} | sed "s/\<${itm2rm}\>//g"\`); done ; echo ${array[@]}
jim 0 26 billy foo bar

回答by Clark Kent

this post had been revised and moved to its own post as a more in-depth tutorial how to remove an array element correctly in a for loop

这篇文章已经过修改并移到自己的帖子中作为更深入的教程如何在 for 循环中正确删除数组元素