In bash, how could I add integers with leading zeroes and maintain a specified buffer

readdit picture readdit · Jul 7, 2010 · Viewed 41.6k times · Source

For example, I want to count from 001 to 100. Meaning the zero buffer would start off with 2, 1, then eventually 0 when it reaches 100 or more.

ex: 001 002 ... 010 011 ... 098 099 100

I could do this if the numbers had a predefined number of zeroes with printf "%02d" $i. But that's static and not dynamic and would not work in my example.

Answer

Dennis Williamson picture Dennis Williamson · Jul 7, 2010

If by static versus dynamic you mean that you'd like to be able to use a variable for the width, you can do this:

$ padtowidth=3
$ for i in 0 {8..11} {98..101}; do printf "%0*d\n" $padtowidth $i; done
000
008
009
010
011
098
099
100
101

The asterisk is replaced by the value of the variable it corresponds to in the argument list ($padtowidth in this case).

Otherwise, the only reason your example doesn't work is that you use "2" (perhaps as if it were the maximum padding to apply) when it should be "3" (as in my example) since that value is the resulting total width (not the pad-only width).