Bash Scripting – How to Create a Sequence with Leading Zeroes Using Brace Expansion

arithmeticbashbrace-expansion

When I use the following, I get a result as expected:

$ echo {8..10}
8 9 10

How can I use this brace expansion in an easy way, to get the following output?

$ echo {8..10}
08 09 10

I now that this may be obtained using seq (didn't try), but that is not what I am looking for.

Useful info may be that I am restricted to this bash version. (If you have a zsh solution, but no bash solution, please share as well)

$ bash -version
GNU bash, version 3.2.51(1)-release (x86_64-suse-linux-gnu)

Best Answer

Prefix the first number with a 0 to force each term to have the same width.

$ echo {08..10}
08 09 10

From the bash man page section on Brace Expansion:

Supplied integers may be prefixed with 0 to force each term to have the same width. When either x or y begins with a zero, the shell attempts to force all generated terms to contain the same number of digits, zero-padding where necessary.

Also note that you can use seq with the -w option to equalize width by padding with leading zeroes:

$ seq -w 8 10
08
09
10

$ seq -s " " -w 8 10
08 09 10

If you want more control, you can even specify a printf style format:

$ seq -s " " -f %02g 8 10
08 09 10
Related Question