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 dyna开发者_如何转开发mic and would not work in my example.
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 your system has it, try seq
with the -w
(--equal-width
) option:
$ seq -s, -w 1 10
01,02,03,04,05,06,07,08,09,10
$ for i in `seq -w 95 105` ; do echo -n " $i" ; done
095 096 097 098 099 100 101 102 103 104 105
In Bash version 4 (use bash -version) you can use brace expansion. Putting a 0
before either limit forces the numbers to be padded by zeros
echo {01..100} # 001 002 003 ...
echo {03..100..3} # 003 006 009 ...
#!/bin/bash
max=100;
for ((i=1;i<=$max;i++)); do
printf "%0*d\n" ${#max} $i
done
The code above will auto-pad your numbers with the correct number of 0's based upon how many digits the max/terminal value contains. All you need to do is change the max
variable and it will handle the rest.
Examples:
max=10
01
02
03
04
05
06
07
08
09
10
max=100
001
002
003
004
005
006
...
097
098
099
100
max=1000
0001
0002
0003
0004
0005
0006
...
0997
0998
0999
1000
# jot is available on FreeBSD, Mac OS X, ...
jot -s " " -w '%03d' 5
jot -s " " -w '%03d' 10
jot -s " " -w '%03d' 50
jot -s " " -w '%03d' 100
If you need to pad values up to a variable number with variable padding:
$values_count=514;
$padding_width=5;
for i in 0 `seq 1 $(($values_count - 1))`; do printf "%0*d\n" $padding_width $i; done;
This would print out 00000, 00001, ... 00513. (I didn't find any of the current answers meeting my need)
精彩评论