Friday, 29 September 2017

How can I join elements of an array in Bash?



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

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...