20

How to add leading zero to bash range?
For example, I need cycle 01,02,03,..,29,30
How can I implement this using bash?

Oleg Razgulyaev
  • 5,757
  • 4
  • 28
  • 28

5 Answers5

25

In recent versions of bash you can do:

echo {01..30}

Output:

01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

Or if it should be comma separated:

echo {01..30} | tr ' ' ','

Which can also be accomplished with parameter expansion:

a=$(echo {01..30})
echo ${a// /,}

Output:

01,02,03,04,05,06,07,08,09,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30
Thor
  • 45,082
  • 11
  • 119
  • 130
21

another seq trick will work:

 seq -w 30

if you check the man page, you will see the -w option is exactly for your requirement:

-w, --equal-width
              equalize width by padding with leading zeroes
Kent
  • 189,393
  • 32
  • 233
  • 301
7

You can use seq's format option:

seq -f "%02g" 30
P.P
  • 117,907
  • 20
  • 175
  • 238
3

A "pure bash" way would be something like this:

echo {0..2}{0..9}

This will give you the following:

00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

Removing the first 00 and adding the last 30 is not too hard!

Neil Winton
  • 286
  • 1
  • 5
  • 1
    The only problem with this solution is that it doesn't work easily when you need a range like 000--135. There is no easy way to stop at 135. – Adam Stewart Aug 11 '19 at 20:55
2

This works:

printf " %02d" $(seq 1 30)
mouviciel
  • 66,855
  • 13
  • 106
  • 140