9

I have an array whose elements may contain spaces:

set ASD "a" "b c" "d"

How can I convert this array to a single string of comma-separated values?

# what I want:
"a,b c,d"

So far the closest I could get was converting the array to a string and then replacing all the spaces. The problem is that this only works if the array elements don't contain spaces themselves

(echo $ARR | tr ' ' ',')

2 Answers 2

14

Since fish 2.3.0 you can use the string builtin:

string join ',' $ASD

The rest of this answer applies to older versions of fish.

One option is to use variable catenation:

echo -s ,$ASD

This adds an extra comma to the beginning. If you want to remove it, you can use cut:

echo -s ,$ASD | cut -b 2-

For completeness, you can also put it after and use sed:

echo -s $ASD, | sed 's/,$//'
1
  • Those cut/sed approaches only work if the elements of the array don't contain newline characters. tail -c +2 would be more appropriate. Commented Feb 5, 2018 at 15:29
2

You can use printf and paste instead of echo and tr:

printf '%s\n' $ASD | paste -sd,

AFAIK, fish has no builtin way for joining array elements.

1
  • 1
    not sure if it was added in the interim or before but the command to join array elements is string join [(-q | --quiet)] SEP [STRING...] - example: string join \n $PATH
    – tbjgolden
    Commented Dec 12, 2020 at 23:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .