首先让我清楚地说明我的问题:
例如:让我们假装这是我的数组,(元素无关紧要,因为我的实际代码有所不同):
array=(jim 0 26 chris billy 78 hello foo bar)
Run Code Online (Sandbox Code Playgroud)
现在说我要删除以下元素:
chris 78 hello
Run Code Online (Sandbox Code Playgroud)
所以我做了:unset array[$i]
循环遍历数组.这会正确地删除元素,但是,我最终得到一个如下所示的数组:
array=(jim 0 26 '' billy '' '' foo bar)
Run Code Online (Sandbox Code Playgroud)
我需要它看起来像这样:
array=(jim 0 26 billy foo bar)
Run Code Online (Sandbox Code Playgroud)
其中吉姆是在索引0,0 @ 1,26 2 @等.
如何删除数组中的元素并移动其他元素,以便数组中没有空/空格?
谢谢!
che*_*ner 23
试试这个:
$ array=( "one two" "three four" "five six" )
$ unset array[1]
$ array=( "${array[@]}" )
$ echo ${array[0]}
one two
$ echo ${array[1]}
five six
Run Code Online (Sandbox Code Playgroud)
Shell数组实际上不是作为可以添加和删除项目的数据结构(它们主要用于为类似情况提供第二级引用)
arr=( "one two" "three four" )
somecommand "${arr[@]}"
Run Code Online (Sandbox Code Playgroud)
提供somecommand
两个,而不是四个参数).但这应该适用于大多数情况.
归档时间: |
|
查看次数: |
16439 次 |
最近记录: |