0

I created an array of a sequence of numbers. How can I check the size of each element, and depending on the number of digits, each element has I want to add more numbers to it. Below I have some code that accomplishes this using one variable, but I want to do it with the array

#array I would like to use 
start=0
end=20
myarray=( $(seq $start  $end) )

#example of how I accomplish this using a variable. checks if the number of integers is between 1-5
and adds some numbers to the end. I would like to accomplish this but with an array.

number=2

local newnum=`expr length "$number"` #get lenght of the variable

if [ "$newnum" -eq "1" ];then 
    number="0000${number}" 

elif [ "$newnum" -eq "2" ];then
      number="000${number}"   

elif [ "$newnum" -eq "3" ];then
     number="00${number}"

elif [ "$newnum" -eq "4" ];then
    number="0${number}"

elif [ "$newnum" -eq "5" ]; then
    echo "you enter five numbers"
    #number remains the size 
else
    exit
fi #end if 







1 Answers1

0

One way:

for val in "${myarray[@]}"
do
    len=${#val}
    echo $val , $len
    ....do action depending on $len .....
done
Guru
  • 16,456
  • 2
  • 33
  • 46
  • Thank you Guru, for your fast response. The solution worked and I learned something new. – paninindicuaro Apr 07 '20 at 03:47
  • Hi Guru, if I start my array sequence from number one the loop does not seem to work. At least it does not seem to work when I put it in the if statement. for example when i start the sequence from 1 I should be getting 00001 from the if statement but instead I get 1 – paninindicuaro Apr 07 '20 at 04:59
  • It looks like you are trying to get the numbers zero padded by 5. You can get it easily. `seq -f "%05g" 1 10` – Guru Apr 07 '20 at 05:35
  • Thank you, Guru, you are amazing. I was able to get rid of 13 lines of code for one line of code. – paninindicuaro Apr 08 '20 at 01:28