Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Range with leading zero in bash

Tags:

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?

like image 609
Oleg Razgulyaev Avatar asked Nov 14 '12 09:11

Oleg Razgulyaev


People also ask

How to iterate range in bash?

You can iterate the sequence of numbers in bash in two ways. One is by using the seq command, and another is by specifying the range in for loop. In the seq command, the sequence starts from one, the number increments by one in each step, and print each number in each line up to the upper limit by default.


2 Answers

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
like image 132
Thor Avatar answered Oct 12 '22 15:10

Thor


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
like image 44
Kent Avatar answered Oct 12 '22 14:10

Kent