Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment a zero padded int in Bash

Tags:

bash

I have a set of records to loop. The numbers range from 0000001 to 0089543 that ill call UIDX.

if i try something like:

for ((i=0; i< 0089543; i++)); do
    ((UIDX++))
done

counter increments 1, 2, 3, 4 as opposed to the 0000001, 0000002... that i need.

what is the best way to pad those leading zero's?

like image 924
Juan Avatar asked Apr 07 '11 16:04

Juan


People also ask

How do I increment an INT in bash?

Similar to other programming language bash also supports increment and decrement operators. The increment operator ++ increases the value of a variable by one. Similarly, the decrement operator -- decreases the value of a variable by one.

What does %% mean in bash?

So as far as I can tell, %% doesn't have any special meaning in a bash function name. It would be just like using XX instead. This is despite the definition of a name in the manpage: name A word consisting only of alphanumeric characters and under- scores, and beginning with an alphabetic character or an under- score.

What does i ++ mean in bash?

The operators can be used before or after the operand. They are also known as: prefix increment: ++i. prefix decrement: --i. postfix increment: i++

What does %f mean bash?

The “[ -f ~/. bashrc]” is known as a test command in bash. This command, which includes the “-f” expression, will check if the ~/. bashrc file exists (i.e. the file .


1 Answers

Use the printf command to format the numbers with leading zeroes, eg:

for ((i = 0; i < 99; ++i)); do printf -v num '%07d' $i; echo $num; done

From man bash:

printf [-v var] format [arguments]
Write the formatted arguments to the standard output under the control of the format. The -v option causes the output to be assigned to the variable var rather than being printed to the standard output.

like image 101
Sean Avatar answered Oct 01 '22 15:10

Sean