Adding Leading Zero in Bash

Karl Auer kauer at biplane.com.au
Sun Oct 22 11:35:03 UTC 2006


On Sun, 2006-10-22 at 13:56 +0300, OOzy Pal wrote:
> How can I add a leading zero to numbers that are from 1 to 9 to be 01,
> 02. . .,09?

It's not bash, but most systems these days have a printf command.

Use this to pad $VAR out to two digits with a zero if necessary:

   printf "%02d" $VAR

To right-justify in a two-digit space:

   printf "%2d" $VAR

To convert a bunch of numbers:

   for x in 0 1 2 3 4 5 6 7 ; { printf "%02d\n" $x ; }

To put the result in a variable, use backticks:

   x=`printf "%02d" 7`
   echo $x
   7

Three-digit numbers will just be printed as is. If you try to format a
non-integer with %d though, printf will issue an error message.

   printf "%02d" blah
   bash: printf: blah: invalid number

See "man printf" for more - there are a zillion formatting options.

Regards, K.

-- 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Karl Auer (kauer at biplane.com.au)                   +61-2-64957160 (h)
http://www.biplane.com.au/~kauer/                  +61-428-957160 (mob)





More information about the ubuntu-users mailing list