Karthik Karthik - 4 months ago 12
Bash Question

Unix: Expressing a number in certain digit format padded with zeroes

How can i express a number with certain number of digits with a command in unix.

Say 7 to be expressed in 6 digits as 000007 and 17 to be 000017. Please let me know if any such command available to achieve this.

Answer

If you're using BASH then you can use printf builtin for zero padding:

printf "%06d\n", 7
000007

printf "%06d\n", 17
000017

If not using BASH then use awk:

awk -v n=17 'BEGIN{printf "%06d\n", n}'
000017

awk -v n=7 'BEGIN{printf "%06d\n", n}'
000007