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
.
Answer
Rewriting solution by Pascal Pilz as a function in 100% pure Bash (no external commands):
function join_by { local IFS="$1"; shift; echo "$*"; }
For example,
join_by , a "b c" d #a,b c,d
join_by / var local tmp #var/local/tmp
join_by , "${FOO[@]}" #a,b,c
Alternatively, we can use printf to support multi-character delimiters, using the idea by @gniourf_gniourf
function join_by { local d=$1; shift; echo -n "$1"; shift; printf "%s" "${@/#/$d}"; }
For example,
join_by , a b c #a,b,c
join_by ' , ' a b c #a , b , c
join_by ')|(' a b c #a)|(b)|(c
join_by ' %s ' a b c #a %s b %s c
join_by $'\n' a b c #abc
join_by - a b c #a-b-c
join_by '\' a b c #a\b\c
No comments:
Post a Comment