If I have an array like this in Bash:
FOO=( a b c )
How do I join the elements with commas? For example, producing a,b,c
.
liststr=""
for item in list
do
liststr=$item,$liststr
done
LEN=`expr length $liststr`
LEN=`expr $LEN - 1`
liststr=${liststr:0:$LEN}
This takes care of the extra comma at the end also. I am no bash expert. Just my 2c, since this is more elementary and understandable
Here's one that most POSIX compatible shells support:
join_by() {
# Usage: join_by "||" a b c d
local arg arr=() sep="$1"
shift
for arg in "$@"; do
if [ 0 -lt "${#arr[@]}" ]; then
arr+=("${sep}")
fi
arr+=("${arg}") || break
done
printf "%s" "${arr[@]}"
}
I would echo the array as a string, then transform the spaces into line feeds, and then use paste
to join everything in one line like so:
tr " " "\n" <<< "$FOO" | paste -sd , -
Results:
a,b,c
This seems to be the quickest and cleanest to me !
Using no external commands:
$ FOO=( a b c ) # initialize the array
$ BAR=${FOO[@]} # create a space delimited string from array
$ BAZ=${BAR// /,} # use parameter expansion to substitute spaces with comma
$ echo $BAZ
a,b,c
Warning, it assumes elements don't have whitespaces.
Here's a single liner that is a bit weird but works well for multi-character delimiters and supports any value (including containing spaces or anything):
ar=(abc "foo bar" 456)
delim=" | "
printf "%s\n$delim\n" "${ar[@]}" | head -n-1 | paste -sd ''
This would show in the console as
abc | foo bar | 456
Note: Notice how some solutions use printf
with ${ar[*]}
and some with ${ar[@]}
? The later ones (with @
) use the printf
feature that support multiple arguments by repeating the format template, while the former ones do not actually need printf
and rely on manipulating the field separator and bash's word expansion and would work just as well with echo
, cat
and others - these solutions likely use printf
because the author doesn't really understand what they are doing, and you should not use them.
My attempt.
$ array=(one two "three four" five)
$ echo "${array[0]}$(printf " SEP %s" "${array[@]:1}")"
one SEP two SEP three four SEP five