Tuesday, May 29, 2012

Right pad a string or a number with zero



 In an earlier article, we saw the different ways in which we can left pad a string with zeros. In this, let us see the different ways in which we can right pad a string or a number with zeros.

  Assuming a number, say 234, which we want to right pad to 7 digits with zeros:

1. This sed way had been discussed in example 4 of left padding a string as well. The same explanation holds good here. Only difference being instead of having a '0' before &, it is after &.
$ echo 234 | sed -e :a -e 's/^.\{1,6\}$/&0/;ta'
2340000
     One thing to note is the number 6(one less than actual, which is 7). This is because once the length of the number reaches 7, sed quits. To understand better, put 7 in place of 6 and check the result.

2.Using awk, a for loop is run till the length of the variable becomes 7. During every iteration, the number is appended a zero.
$ echo 234 | awk '{x=$0;for(i=length;i<7;i++)x=x "0";}END{print x}'
2340000
3. A typical shell script. Approach is same as the awk approach.
#!/bin/bash
num="234"
len=`echo ${#num}`
while [ $len -lt 7 ];
do
        num=$num"0"
        let len=len+1
done
echo $num
   The length of the variable is calculated first. A while loop is run till the length becomes 7.let command in shell allows us to do arithmetic operations in shell.

4. The perl way, a little interesting.
$ echo "234" | perl -pne '$len=7+1-length;$_=~s/$/"0" x $len/e;'
2340000
  The length is calculated first using the length function of perl. The variable len  contains the digits to be filled with zeros. The -1 is needed since the length function also takes the newline into account. The substitution(s) function is used wherein at the end($) of the line, we add as many 0's as is the len variable. The e switch is needed to evaluate the substitution part as an expression. i.e, "0" x $len means repeat "0" len times.

5. Another way using perl. Keep multiplying the number by 10 till the length reaches 7. $_ denotes the current line in perl.
$ echo 234 | perl -pne 'while(length($_) < 7){$_*=10;}'
2340000

No comments:

Post a Comment