我怎样才能在一个数组中删除一个元素,然后在Shell脚本的阵列转移? [英] How can i delete an element in an array and then shift the array in Shell Script?
问题描述
首先让我清楚说明我的问题:
First let me state my problem clearly:
例如:让我们pretend这是我的数组(元素并不重要,在我的实际code,他们有所不同):
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
所以,我做:取消设置阵列[$ i]
,同时通过数组循环。
这消除了正确的元素,但是,我结束了一个数组,看起来像这样:
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:
array=(jim 0 26 '' billy '' '' foo bar)
我需要它看起来像这样:
I need it to look like this:
array=(jim 0 26 billy foo bar)
其中的吉姆的是指数的 0 的 0 @ 1 的 26 @ 2 的等。
where jim is at index 0, 0@1, 26@2, etc..
如何删除数组中的元素和移动其它元件,以便有没有空/阵列中的空的空间?
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?
谢谢!
推荐答案
试试这个:
$ 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
arr=( "one two" "three four" )
somecommand "${arr[@]}"
为 somecommand
有两个,不是四个,参数)。但是,这在大多数情况下工作。
to provide somecommand
with two, not four, arguments). But this should work in most situations.
这篇关于我怎样才能在一个数组中删除一个元素,然后在Shell脚本的阵列转移?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!