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.
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.
$0 or ${0} is the name used to invoke the current shell or script.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With