Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a value into the middle of an array?

Tags:

arrays

bash

Hello I have the following array:

array=(1 2 3 4 5 7 8 9 12 13)

I execute this for loop:

    for w in ${!array[@]}
    do
        comp=$(echo "${array[w+1]} - ${array[w]} " | bc)
        if [ $comp = 1 ]; then
            /*???*/
        else
            /*???*/
        fi
    done

What I would like to do is to insert a value when the difference between two consecutive elements is not = 1

How can I do it?

Many thanks.

like image 465
Andrea Avatar asked Sep 05 '25 18:09

Andrea


2 Answers

Just create a loop from the minimum to the maximum values and fill the gaps:

array=(1 2 3 4 5 7 8 9 12 13)
min=${array[0]}
max=${array[-1]}

new_array=()
for ((i=min; i<=max; i++)); do
    if [[ " ${array[@]} " =~ " $i " ]]; then
        new_array+=($i)
    else
        new_array+=(0)
    fi
done

echo "${new_array[@]}"

This creates a new array $new_array with the values:

1 2 3 4 5 0 7 8 9 0 0 12 13

This uses the trick in Check if an array contains a value.

like image 79
fedorqui 'SO stop harming' Avatar answered Sep 08 '25 08:09

fedorqui 'SO stop harming'


You can select parts of the original array with ${arr[@]:index:count}.
Select the start, insert a new element, add the end.

To insert an element after index i=5 (the fifth element)

 $ array=(1 2 3 4 5 7 8 9 12 13)
 $ i=5
 $ arr=("${array[@]:0:i}")         ### take the start of the array.
 $ arr+=( 0 )                      ### add a new value ( may use $((i+1)) )
 $ arr+=("${array[@]:i}")          ### copy the tail of the array.
 $ array=("${arr[@]}")             ### transfer the corrected array.
 $ printf '<%s>' "${array[@]}"; echo
 <1><2><3><4><5><6><7><8><9><12><13>

To process all the elements, just do a loop:

 #!/bin/bash

array=(1 2 3 4 5 7 8 9 12 13)

for (( i=1;i<${#array[@]};i++)); do

    if    (( array[i] != i+1 ));
    then  arr=("${array[@]:0:i}")           ### take the start of the array.
          arr+=( "0" )                      ### add a new value
          arr+=("${array[@]:i}")            ### copy the tail of the array.
          # echo "head $i ${array[@]:0:i}"  ### see the array.
          # echo "tail $i ${array[@]:i}"
          array=("${arr[@]}")               ### transfer the corrected array.
    fi
done
printf '<%s>' "${array[@]}"; echo

$ chmod u+x ./script.sh
$ ./script.sh
<1><2><3><4><5><0><7><8><9><10><0><0><13>