4

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)

Tim Eagle
  • 51
  • 1
  • 7

4 Answers4

12

Use parameter expansion:

DATES=( ${DATES[@]#0} )
choroba
  • 231,213
  • 25
  • 204
  • 289
  • 3
    You can use [`shopt -s extglob; DATES=("${DATES[@]##+(0)}")`](http://stackoverflow.com/questions/8078167/bizarre-issue-with-printf-in-bash-script09-and-08-are-invalid-numbers-07#comment9903141_8078505) to remove any number of zeros. – l0b0 Jun 05 '13 at 14:53
  • Be careful when using @l0b0 suggestion. This will remove not only padded 0's but also the value "0" by itself as well. My script required supporting "0". Therefore I needed to build in more logic to recognize if "0" existed before using the `shopt` command, then re-adding "0" to my array at the end after all grooming was complete. – Dave Nov 22 '20 at 20:14
4

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
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • +1 for `10#$day`, but how would you apply it to the current issue? – l0b0 Jun 05 '13 at 14:37
  • Well, the question says "remove the leading zeroes...so i can iterate in another step". There's no need to remove the zeros in the first place. – glenn jackman Jun 05 '13 at 15:38
  • I mean OP specifically asked about an *array*. – l0b0 Jun 05 '13 at 21:06
  • 1
    I know, but sometimes we shouldn't give people exactly what they ask for ([xy problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)) – glenn jackman Jun 05 '13 at 21:23
1

You can use bash parameter expansion (see http://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html) like this:

echo ${DATESLZ[@]#0}
blue
  • 2,683
  • 19
  • 29
0

If: ${onedate%%[!0]*} will select all 0's in front of the string $onedate.

we could remove those zeros by doing this (it is portable):

echo "${onedate#"${onedate%%[!0]*}"}"

For your case (only bash):

#!/bin/bash
dates=( 01 02 02 08 10 18 20 21 0008 00101 )

for onedate in "${dates[@]}"; do
    echo -ne "${onedate}\t"
    echo "${onedate#"${onedate%%[!0]*}"}"
done

Will print:

$ script.sh
01      1
02      2
02      2
08      8
10      10
18      18
20      20
21      21
0008    8
00101   101