0

I'm trying to use Bash string substitution to combine an array. Desired output:

cat,dog,fish

This works, but isn't there a way to do with without piping?

#!/bin/bash

words=(cat dog fish)

echo "${words[@]}" | sed 's/ /,/g'

I've been trying this, which doesn't work.

echo "${words[@]// /,/}"
  • @AdminBee , so it's not possible with string substitution? – user428109 Aug 13 '20 at 07:58
  • Not in the way you suppose, because the individual array elements are the "bare" words without leading or trailing space - there simply is no space that you could substitute with a ,. You only use spaces when filling the array with a list, to indicate to bash where one element ends and the next one starts. You could just as well have said declare -A words; words[1]="cat"; words[2]="dog"; words[3]="fish" and get the same array content. – AdminBee Aug 13 '20 at 08:23

0 Answers0