Tell me more ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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)
share|improve this question
Some hint to do this in bash 3 I found here: mywiki.wooledge.org/BashFAQ/018 However, the approach outlined there is not convenient. – Bernhard Jan 4 at 9:06

3 Answers

up vote 1 down vote accepted

Use a range that starts with a constant digit and strip that digit off:

echo \ {108..110} | sed 's/ 1//g'

or without using an external command:

a=({108..110}); echo "${a[@]#1}"

For use in a for loop:

for x in {108..110}; do
  x=${x#1}
  …
done

though for this case a while loop would be clearer and works in any POSIX shell:

x=8
while [ $x -le 10 ]; do
  n=$((100+x)); n=${n#1}
  …
  x=$((x+1))
done
share|improve this answer
I accepted this answer above the other answers, because it satisfies the request for Bash 3.x. Especially as I needed the for loop anyhow. – Bernhard Jan 25 at 23:06

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
share|improve this answer
After just found out about the echo {08..10} solution, however, it is only introduced for bash version 4 and up. – Bernhard Jan 4 at 9:05

if you use printf

printf "%.2d " {8..10} 

this will force to be 2 chars and will add a leading 0. In case you need 3 digits you can change to "%.3d ".

share|improve this answer
Thanks for your answer. I am aware of the printf solution, but it is not really making this easier. I am hoping that there is some hidden trick that does the job :) – Bernhard Jan 4 at 8:49

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.