How to output comma-separated strings using bash brace expansion

It seems bash does not use $IFS to join the generated words. Another technique would be to store the generated words in an array and then $IFS will be in play:

I'm going to use a subshell so I don't alter this shell's IFS: pick one of

( words=( a{b,c,d} ); IFS=,; echo "${words[*]}" )
( set -- a{b,c,d}; IFS=,; echo "$*" )

That emits the comma-separates string to stdout. If you want to capture it:

joined=$( set -- a{b,c,d}; IFS=,; echo "$*" )

Assuming that the elements do not contain spaces, you could translate spaces to commas:

echo a{b,c,d} | tr ' ' ,

which produces:

ab,ac,ad

You can also use ranges with characters:

echo a{b..d} | tr ' ' ,

This is especially useful if you want a larger range.


I am sure there are many ways to accomplish this. Here is one method:

echo a{b,c,d} | sed 's/ /,/g'

Tags:

Shell

Bash