Oleg Razgulyaev
Oleg Razgulyaev

Reputation: 5935

Range with leading zero in bash

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?

Upvotes: 21

Views: 8451

Answers (5)

Thor
Thor

Reputation: 47109

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

Upvotes: 27

Kent
Kent

Reputation: 195109

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

Upvotes: 21

Neil Winton
Neil Winton

Reputation: 286

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!

Upvotes: 3

P.P
P.P

Reputation: 121397

You can use seq's format option:

seq -f "%02g" 30

Upvotes: 7

mouviciel
mouviciel

Reputation: 67849

This works:

printf " %02d" $(seq 1 30)

Upvotes: 2

Related Questions