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

前端 未结 4 1003
迷失自我
迷失自我 2021-01-01 23:46

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         


        
相关标签:
4条回答
  • 2021-01-01 23:53

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

    1. Remove an Element from an Array

    ...

    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.

    0 讨论(0)
  • 2021-01-02 00:01

    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

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

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

    0 讨论(0)
  • 2021-01-02 00:04

    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
    
    0 讨论(0)
  • 2021-01-02 00:05

    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

    0 讨论(0)
提交回复
热议问题