1

I would like to apply parameter expansion (e.g. search and replace) in order to remove spaces from the brace expansion ({a..z}). It is possible?

So I've the following range: {a..z} which consist all letters and I would like to remove spaces in one go.

Here is longer example:

$ echo {a..z}
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
$ az=$(eval echo {a..z})
$ echo $az
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
$ echo ${az// /}
abcdefghijklmnopqrstuvwxyz

Is it possible to apply parameter expansion directly on a range? Or at least to make it in one expression, especially without assigning this to variable?


One example usage is to specify all parameters dynamically for getopts, for example:

while getopts {a..z} arg; do
  printf $arg
done

however this doesn't work (e.g. ./az.sh -a -b -c) as spaces from that range needs to be removed first.

kenorb
  • 155,785
  • 88
  • 678
  • 743

2 Answers2

3

Use this code instead:

$ printf '%s' {a..z}; echo
abcdefghijklmnopqrstuvwxyz

And this if you need to use a var (bash):

$ printf -v var '%s' {a..z}
$ echo "$var"
abcdefghijklmnopqrstuvwxyz

Parameter expansion only could be applied to a Parameter (hence it's name).
So no, you could not apply "Parameter expansion" to a "Brace Expansion".
It must be in two steps:

var="$(printf '%s ' {a..z})"
var="${var// /}"

So getopts example would look like:

while getopts "$(printf '%s' {a..z})" arg; do
  printf '%s' "$arg"
done
0
$ set {m..z} && IFS=, && echo "$*"
m,n,o,p,q,r,s,t,u,v,w,x,y,z
$ set {m..z} && IFS='' && echo "$*"
mnopqrstuvwxyz
mauro
  • 5,730
  • 2
  • 26
  • 25