Adding Leading Zero in Bash

Felipe Alfaro Solana felipe.alfaro at gmail.com
Sun Oct 22 17:20:32 UTC 2006


On 10/22/06, OOzy Pal <oozypal at gmail.com> wrote:
> Ok, but I don't know number before hand, I mean that I might come a
> cross 15. Then what would happend am I gona get 015.
>
> I would like to add zero when the number is between 0-9 and ignors the
> zero for number >9

$ echo 3 | sed 's/^\([0-9]\)$/0\1/g'
03
$ echo 12 | sed 's/^\([0-9]\)$/0\1/g'
12

However, depending on what you are trying to do, this can be very
slow, specially if used within a loop. So, chances are that you want
to use:

NUMBER="1"
if [ "${#NUMBER}" == 1 ]; then
  echo "0${NUMBER}";
else
  echo "$NUMBER";
fi

And, if you want to be sure that NUMBER is a number:

if echo "$NUMBER" | grep -q '^[0-9]\+$'; then
  echo "$NUMBER is a number"
fi




More information about the ubuntu-users mailing list