Karthik Karthik - 1 year ago 39
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 Source

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

printf "%06d\n", 7

printf "%06d\n", 17

If not using BASH then use awk:

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

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