New answer using %08.0f
As %f
is used to print decimal floating point, argument must be decimal.
So there is no risk to see argument interpreted as octal:
Do simply:
a=0010
a=`printf %08.0f $a`
or
a=$(printf %08.0f $a)
then
echo $a
00000010
This work find under any POSIX shell
Using bash, you could avoid fork by using -v
option of printf
:
a=0010
printf -v a %08.0f $a
echo $a
00000010
Old answer (using %d
)
Under POSIX shell
You can drop the left 0
character with the following:
a=00010
while [ "$a" != "${a#0}" ] ;do a=${a#0};done
printf "%08d" $a
00000010
As this doesn't fork a new command session, this could be quicker than using sed
.
You can force decimal interpretation with the following syntax:
a=000010
printf "%08d" $((10#$a))
00000010
This could be useful for conversions:
a="0a"
printf "%04d" $((16#$a))
0010
a="00001010"
printf "%04d" $((2#$a))
0010
a="00012"
printf "%04d" $((8#$a))
0010
a="0020"
printf "%04d" $((5#$a))
0010
a="0013"
printf "%04d" $((7#$a))
0010
and so on...
a="zz"
printf "%04d" $((36#$a))
1295