Digits with starting zero's in loops

Hi friends,

I have 2 requirements on numbers with starting zero's to make them having equal number of digits.

  1. To setup a for loop for 1-100, it can be done by
for ((i=1;i<=100;i++))
do 
echo $i 
done

but I need to setup them like 001,002,003,004 ...100. How can I achieve this?

  1. I am increasing the count on one variable by looping from another variable like
cnt=001
for fil in *
do
blah blah...
blah blah..
cnt=`expr $cnt +1`
done

In the above loop I need the values of cnt as 001,002,003 etc...

Please advise how can I achieve them, thanks a lot!!

printf "%03d\n" $i

or do it with the seq command if installed.

seq -w 1 100

Hi.
Minor alteration to code from frank_rizzo:

printf "%03d\n" {1..10}

producing:

001
002
003
004
005
006
007
008
009
010

Best wishes ... cheers, drl

not very portable but bash4 does for i in {001..100} with zero-padding.
you can also use printf -v to save a subshell.

  for ((i=0;i<=100;i++));do
    printf -v j '%03d' "$i"
    echo "$j"
  done

You could also (depending on your shell, which you haven't told us, but it looks like bash)

typeset -Z3 i

This will set the value to be three digits with leading zeros as required. As a caution though, it will use the right-most three digits it your value is higher.

This can be useful sometimes, but can get in the way:-

$ typeset -Z3 i=1234
$ echo $i
234

I hope that this helps,
Robin
Liverpool/Blackburn
UK