2

I am running Debian 9. In Bash I can echo {a..z} for the alphabet, or echo {a..z}{a..z} to print letter combinations. However, I would like to generate an index with: a b c d etc. then aa bb cc dd etc. then aaa bbb ccc ddd etc. until it is aaaaa bbbbb (until zzzzz). How could this be done with brace expansion or another similar method? Thanks

4

You could do:

$ printf '%s ' {a..z}; echo
a b c d e f g h i j k l m n o p q r s t u v w x y z

$ printf '%s%s ' {a..z}{,}; echo
aa bb cc dd ee ff gg hh ... ss tt uu vv ww xx yy zz 

$ printf '%s%s%s ' {a..z}{,,}
aaa bbb ccc ddd eee ... ttt uuu vvv www xxx yyy zzz

Explained: A brace expansion will create one argument per each value delimited by the comma (and the leading string):

$ echo A{d,u,j}
Ad Au Aj

But, if the value is empty, it will just repeat the leading string:

$ echo A{,,}
A A A

If the leading string is itself a brace expansion, all its strings will be repeated:

$ echo {one,two}{,,}
one one one two two two

Then, the printf (and the trailing echo) are used to format the output:

$ printf '%s%s%s ' {one,two}{,,}; echo
oneoneone twotwotwo

With one letter values:

$ printf '%s%s%s ' {a..d}{,,}; echo
aaa bbb ccc ddd
  • This is a fairly clever answer, and I would probably have upvoted it if you had explained how it works! – G-Man Says 'Reinstate Monica' Oct 16 '18 at 3:52
  • @G-Man Better now? – Isaac Oct 16 '18 at 21:08
1

AFAIK you can't do this purely by having bash do some expansion magic. But you can always use

for c in {a..z}; do echo $c$c; done
for c in {a..z}; do echo $c$c$c; done
...
0

Here is another option in Bash.

index=$(echo -n {a..z})
num=2
until ((num>5)); do
    for c in {a..z}; do
        case "$num" in
            2 ) index=$(echo -n "$index $c$c") ;;
            3 ) index=$(echo -n "$index $c$c$c") ;;
            4 ) index=$(echo -n "$index $c$c$c$c") ;;
            5 ) index=$(echo -n "$index $c$c$c$c$c") ;;
        esac
    done
((num++))
done
echo "$index"
  1. Add the first set to the index.
  2. Loop four times for the remaining four sets.
  3. Run for loop for each letter.
  4. The case statement in the for loop determines the number of instances each letter is added to the index.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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