Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove leading zero from BASH array variables

Tags:

bash

sed

awk

I am trying to remove leading zeroes from a BASH array... I have an array like:

echo "${DATES[@]}"

returns

01 02 02 03 04 07 08 09 10 11 13 14 15 16 17 18 20 21 22 23

I'd like to remove the leading zeroes from the dates and store back into array or another array, so i can iterate in another step... Any suggestions?

I tried this,

for i in "${!DATES[@]}"
do
    DATESLZ["$i"]=(echo "{DATES["$i"]}"| sed 's/0*//' ) 
done

but failed (sorry, i'm an old Java programmer who was tasked to do some BASH scripts)

like image 750
Tim Eagle Avatar asked Dec 02 '22 23:12

Tim Eagle


2 Answers

Use parameter expansion:

DATES=( ${DATES[@]#0} )
like image 80
choroba Avatar answered Dec 27 '22 22:12

choroba


With bash arithmetic, you can avoid the octal woes by specifying your numbers are base-10:

day=08
((day++))           # bash: ((: 08: value too great for base (error token is "08")
((day = 10#$day + 1))
echo $day              # 9
printf "%02d\n" $day   # 09
like image 25
glenn jackman Avatar answered Dec 27 '22 21:12

glenn jackman