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)

2
  • What about just printf "%d" $DATES for each item? Commented Jun 5, 2013 at 12:40
  • 4
    @fedorqui, this is why: printf "%d" 08 ==> bash: printf: 08: invalid octal number Commented Jun 5, 2013 at 15:40

4 Answers 4

12

Use parameter expansion:

DATES=( ${DATES[@]#0} )
Sign up to request clarification or add additional context in comments.

2 Comments

You can use shopt -s extglob; DATES=("${DATES[@]##+(0)}") to remove any number of zeros.
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.
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

4 Comments

+1 for 10#$day, but how would you apply it to the current issue?
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.
I mean OP specifically asked about an array.
I know, but sometimes we shouldn't give people exactly what they ask for (xy problem)
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}

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.