0

I'm trying to use string substitution to combine an array. Output:

a,b,c

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

#!/bin/bash

words=(a b c)

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

I've tried this, which doesn't work.

echo "${words[@]// /,/}"
4
  • 1
    Duplicate of unix.stackexchange.com/questions/604271/… which was written 30 min prior and was also closed as a duplicate of unix.stackexchange.com/questions/389369/…
    – Stewart
    Aug 13, 2020 at 8:17
  • @Stewart , Because it's not a duplicate. And thank you Kusalananda for the proposed answer
    – user428109
    Aug 13, 2020 at 8:20
  • 1
    @user428109 In what way is it not a duplicate? Well, that question asks for a function. The difference here is minimal.
    – Kusalananda
    Aug 13, 2020 at 8:20
  • 1
    Please don't do this. If your question is closed and you don't believe it is a duplicate, then edit the closed question to make the difference clear and it can be reopened. If you just post the same question again, you create more work for us, more clutter for the site.
    – terdon
    Aug 13, 2020 at 8:34

1 Answer 1

4

If you want to output a string consisting of the elements of an array delimited by a particular character, then use

words=(a b c)

( IFS=,; printf '%s\n' "${words[*]}" )

Using * in place of @ in "${words[*]}" will create a single string out of the concatenation of all elements of the array words. The elements will be delimited by the first character of $IFS, which is why we set this to a comma before doing the expansion.

I set IFS in a subshell to avoid inadvertently setting it for any other operation than the single expansion needed to create the comma-delimited string for the printf call.

Instead of using a subshell to set IFS locally, you may instead set it and then reset it:

words=(a b c)

IFS=,$IFS
printf '%s\n' "${words[*]}"
IFS=${IFS#?}

This first adds a comma as the first character of $IFS, retaining the old value of the variable as the characters after the comma.

The parameter substitution ${IFS#?} would delete the first character (the comma that we added).

Not the answer you're looking for? Browse other questions tagged or ask your own question.