1

I want to join array elements by using parameter expansion syntax on them and expect following code to work:

declare -a nums=( {1..10} )
echo ${nums[@]// /,}
1 2 3 4 5 6 7 8 9 10
#but
echo ${nums[@]//1/,}
, 2 3 4 5 6 7 8 9 10

Can I make substitution work on white spaces?

James Brown
  • 36,089
  • 7
  • 43
  • 59
l00p
  • 392
  • 2
  • 17
  • You can apply PE to individual elements of the array (because they are treated as strings), but _not_ the content of the array as a whole – Inian Oct 28 '20 at 11:00
  • See [How can I join elements of an array in Bash?](https://stackoverflow.com/q/1527049/5291015) – Inian Oct 28 '20 at 11:02

1 Answers1

4

${nums[@]}" is not a string but an array of 10 numbers which is the reason that substituting space with comma doesn't work as there is no space in array.

You can get array content in a string and do string replacement:

declare -a nums=( 1 2 3 4 5 6 7 8 9 10 )
s="${nums[*]}"
echo "${s// /,}"
1,2,3,4,5,6,7,8,9,10

Or one liner:

IFS=, && printf '%s\n' "${nums[*]}" && unset IFS
anubhava
  • 761,203
  • 64
  • 569
  • 643