bash array operations

Contributor Icon Contributed by hpx Date Icon June 8, 2005  
Tag Icon Tagged: Bourne shell scripting

sometimes we need to remove one element from an array
for example we remove the element 2 (third) from array



array=(”hello” “i” “like” “bash”)
i=2
array=(${array[@]:0:$i} ${array[@]:$(($i + 1))})

Previous recipe | Next recipe |
 
  • Anonymous
    so looking at the tip found here:
    http://www.tech-recipes.com/bourne_shell_script...

    :oops: works as long as you do not try and remove element 0. Look at just this part:
    ${array[@]:0:$i}
    and you will notice the array is rebuilt using items 0 through $i. The 0 will cause element 0 to stay in the array even if i=0
    Does anyone have a better fix than this:
    #remove i from array
    if [ $i -ne 0 ]; then
    array=( ${array[@]:0:$i} ${array[@]:$(($i + 1))} )
    else
    array=( ${array[@]:$(($i + 1))} )
    fi
  • Anonymous
    #remove i from array
    unset array[$i]
    array=( ${array[@]} )
  • cori_chenxx
    unset command is enough
  • DemonWeasel
    #a function to create a new array minus the specified element

    function remel() {
    array=( `eval echo '${'$1"[@]"'}'` )
    i=$2
    #remove EL from array
    if [ $i -ne 0 ]; then
    array=( ${array[@]:0:$i} ${array[@]:$(($i + 1))} )
    else
    array=( ${array[@]:$(($i + 1))} )
    fi
    echo ${array[@]}
    }

    #to use it:
    arr=( a b c d )
    echo ${arr[@]}
    echo ${arr[1]}
    #to remove element 1 set the array equal to an array of the output
    arr=( `remel arr 1` )
    echo ${arr[@]}
    echo ${arr[1]}
  • DemonWeasel
    or if you want a more standard syntax of taking an array in as a parameter

    function remel(){
    array=( $@ )
    let ind=${#array[@]}-1
    i=${array[$ind]}
    unset array[$ind]
    if [ $i -ne 0 ]; then
    array=( ${array[@]:0:$i} ${array[@]:$(($i + 1))} )
    else
    array=( ${array[@]:$(($i + 1))} )
    fi
    echo ${array[@]}
    }

    #to use it:
    arr=( a b c d )
    echo ${arr[@]}
    echo ${arr[1]}
    #to remove element 1 set the array equal to an array of the output
    arr=( `remel ${arr[@]} 1` )
    echo ${arr[@]}
    echo ${arr[1]}
  • DemonWeasel
    and...here's the real solution...

    function remel() {
    array=$1
    i=$2
    if [ $i -ne 0 ]; then
    eval "$array"="( `eval echo \$\{$array[@]:0:$i\} \$\{$array[@]:$(($i + 1))\}` )";
    else
    eval "$array"="( `eval echo \$\{$array[@]:$(($i + 1))\}` )";
    fi
    }

    #to use it:
    arr=( a b c d )
    echo ${arr[@]}
    echo ${arr[1]}
    #now it actually just removes the element...
    remel arr 1
    echo ${arr[@]}
    echo ${arr[1]}
blog comments powered by Disqus