Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 916
readdit Avatar asked Jul 07 '10 00:07

readdit


People also ask

How do I add leading zeros in Linux?

By Extracting the Filename and Extension In the above example, we've used the %04d format specified with the printf command. It adds leading zeros to a number to make it a four-digit number.

What is ${ 0 * in shell script?

$0 or ${0} is the name used to invoke the current shell or script.


1 Answers

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).

like image 187
Dennis Williamson Avatar answered Sep 18 '22 22:09

Dennis Williamson