Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 如何删除数组中的元素,然后在Shell脚本中移动数组?_Bash_Shell - Fatal编程技术网

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

Bash 如何删除数组中的元素,然后在Shell脚本中移动数组?,bash,shell,Bash,Shell,首先让我清楚地说明我的问题: Ex:让我们假设这是我的数组(元素并不重要,因为在我的实际代码中它们是不同的): 现在,假设我要删除以下元素: chris 78 hello 所以我在循环数组时做了:unset数组[$I]。 这将正确地删除元素,但是,我最终得到一个如下所示的数组: array=(jim 0 26 '' billy '' '' foo bar) array=(jim 0 26 billy foo bar) 我需要它看起来像这样: array=(jim 0 26 '' billy

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

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

现在,假设我要删除以下元素:

chris 78 hello
所以我在循环数组时做了:
unset数组[$I]
。 这将正确地删除元素,但是,我最终得到一个如下所示的数组:

array=(jim 0 26 '' billy '' '' foo bar)
array=(jim 0 26 billy foo bar)
我需要它看起来像这样:

array=(jim 0 26 '' billy '' '' foo bar)
array=(jim 0 26 billy foo bar)
其中jim的索引为0,0@1, 26@2等等

如何删除数组中的元素并移动其他元素,以使数组中没有空/空的空格

谢谢

试试这个:

$ array=( "one two" "three four" "five six" )
$ unset array[1]
$ array=( "${array[@]}" )
$ echo ${array[0]}
one two
$ echo ${array[1]}
five six
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
Shell数组并不是真正用来作为数据结构,您可以从中添加和删除项(它们主要用于为以下情况提供第二级引用:

arr=( "one two" "three four" )
somecommand "${arr[@]}"
somecommand
提供两个而不是四个参数)。但这在大多数情况下都应该有效。

请参阅

  • 从数组中删除元素
  • 这会收缩原始海报所需的pos周围的阵列。

    尝试以下操作:

    $ array=( "one two" "three four" "five six" )
    $ unset array[1]
    $ array=( "${array[@]}" )
    $ echo ${array[0]}
    one two
    $ echo ${array[1]}
    five six
    
    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
    
    user@pc:~$array=(吉姆0 26克里斯比利78你好福巴)
    user@pc:~$itm2rm在克里斯78你好;do array=(\`echo${array[@]}sed“s//\//g”\`);完成;echo${array[@]}
    吉姆0 26比利富酒吧
    
    这篇文章已被修改,并作为更深入的教程转移到了自己的文章中

    很抱歉,我迟了一点才将其标记为正确。它帮助了我。谢谢