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[@]// /,/}"
Kusalananda
  • 333,661
  • 1
    Duplicate of https://unix.stackexchange.com/questions/604271/how-to-combine-array-items-with-string-substitution which was written 30 min prior and was also closed as a duplicate of https://unix.stackexchange.com/questions/389369/how-do-i-join-an-array-of-strings-where-each-string-has-spaces – Stewart Aug 13 '20 at 08:17
  • @Stewart , Because it's not a duplicate. And thank you Kusalananda for the proposed answer – user428109 Aug 13 '20 at 08: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 '20 at 08: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 '20 at 08:34

1 Answers1

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).

Kusalananda
  • 333,661