Thursday, April 26, 2012

How to zero pad a number or a variable?



  In this article, we will see the different ways in which we can do zero padding of a number or a variable or in other words, to put leading zeros to a number. Let us assume a variable "x" whose value is 23, and try to zero pad it to a length of 4.

1. Using printf command:
This is the simplest of all, and efficient too since it uses an internal command printf. The format specifier 4d will align the variable towards the right by 4 digits. By putting 04d, the same number will be zero padded 4 places to the right.
$ x=23
$ printf "%04d\n" $x
0023
2.  Using typeset command:
Another internal command typeset. Earlier, we had seen the usage of typeset in arithmetic operations. typeset has an option -Z which is used for zero padding. So, just declare a variable using typeset with the required padding as shown below
$ typeset -Z4 x
$ x=23
$ echo $x
0023
Note: This option -Z in typeset is not present in all the shells. ksh has this option.

3.  Using awk:
The printf statement in awk also can get the same as the shell printf command:
$ x=23
$ echo $x | awk '{printf "%04d\n", $0;}'
0023
4.  Using sed:
This is my favorite, and little tricky too. This is the same way as we had used in the sed option of our earlier article joining all lines in a file.  t in sed is used for looping. The loop condition here is till the length reaches 4(initial dot(.) + 3). Till 4 character limit is reached, we keep adding 0 in the beginning of the variable.
$ x=23
$ echo $x | sed -e :a -e 's/^.\{1,3\}$/0&/;ta'
0054
  The sed works like this: match any character(.), and match 1 to 3 characters of the same type(1,3). If match successful, put a '0' infront of the pattern matched(&). When the match fails which means when the count of characters excluding the first character exceeds 3, stop it and hence we get the number zero padded by 4.

5.  Shell Script solution:
The traditional way of doing using the while loop. In the while loop, the loop is run till the length of the string or number reaches 4. Till it reaches, a '0' is put in the beginning of the variable.
$ x=23
$ while [ ${#x} -ne 4 ];
> do
>   x="0"$x
> done
$ echo $x
0023
Related Posts Plugin for WordPress, Blogger...

2 comments:

  1. What a classic. Hats off really. Helped me save so much of time.
    God Bless

    ReplyDelete
  2. Thanks for providing so many different ways to accomplish the task - very helpful!

    ReplyDelete