Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to zero pad a sequence of integers in bash so that all have the same width?

I need to loop some values,

for i in $(seq $first $last) do     does something here done 

For $first and $last, i need it to be of fixed length 5. So if the input is 1, i need to add zeros in front such that it becomes 00001. It loops till 99999 for example, but the length has to be 5.

E.g.: 00002, 00042, 00212, 012312 and so forth.

Any idea on how i can do that?

like image 679
John Marston Avatar asked Jan 09 '12 14:01

John Marston


People also ask

What is SEQ 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.

How do I remove leading zeros in bash?

As $machinenumber that is used has to have a leading zero in it for other purposes, the idea is simply to create a new variable ( $nozero ) based on $machinenumber , where leading zeros are stripped away. $machinetype is 74 for now and hasn't caused any problems before.

How do I find the length of a string in bash?

We can use the # operator to get the length of the string in BASH, we need to enclose the variable name enclosed in “{ }” and inside of that, we use the # to get the length of the string variable. Thus, using the “#” operator in BASH, we can get the length of the string variable.


1 Answers

In your specific case though it's probably easiest to use the -f flag to seq to get it to format the numbers as it outputs the list. For example:

for i in $(seq -f "%05g" 10 15) do   echo $i done 

will produce the following output:

00010 00011 00012 00013 00014 00015 

More generally, bash has printf as a built-in so you can pad output with zeroes as follows:

$ i=99 $ printf "%05d\n" $i 00099 

You can use the -v flag to store the output in another variable:

$ i=99 $ printf -v j "%05d" $i $ echo $j 00099 

Notice that printf supports a slightly different format to seq so you need to use %05d instead of %05g.

like image 126
Dave Webb Avatar answered Sep 18 '22 13:09

Dave Webb