Patrick Reis de Souza
Patrick Reis de Souza

Reputation: 33

Zero padding numbers in a Bash loop

I'm trying to make a list with a simple bash looping

I want this:

000000
000001
000002

They give me this:

0
1
2

My shell code:

countBEG="000000"
countEND="999999"


while [ $countBEG != $countEND ]
do
        echo "$countBEG"
        countBEG=$[$countBEG +1]
done

Upvotes: 2

Views: 1843

Answers (3)

glenn jackman
glenn jackman

Reputation: 247182

You're looking for:

seq -w "$countBEG" "$countEND"

The -w option does the padding.

Upvotes: 2

Aaron
Aaron

Reputation: 24812

The following command will produce the desired output (no need for the loop) :

printf '%06d\n' {1..999999}

Explanation :

  • {1..999999} is expanded by bash to the sequence of 1 to 999999
  • the format string '%06d\n' tells printf to display the number it is given as argument padded to 6 digits and followed by a linefeed
  • printf repeats this output if it is given more arguments than is defined in its format specification

Upvotes: 1

Vasan
Vasan

Reputation: 4956

Change your echo to use printf, where you can specify format for left padding.

printf "%06d\n" "$countBEG"

This sets 6 as fixed length of the output, using zeros to fill empty spaces.

Upvotes: 3

Related Questions