How can I join elements of an array in Bash?

2019-01-01 07:38发布

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.

标签: arrays bash
27条回答
梦醉为红颜
2楼-- · 2019-01-01 08:23

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 #a<newline>b<newline>c
join_by - a b c #a-b-c
join_by '\' a b c #a\b\c
查看更多
姐姐魅力值爆表
3楼-- · 2019-01-01 08:23

With re-use of @doesn't matters' solution, but with a one statement by avoiding the ${:1} substition and need of an intermediary variable.

echo $(printf "%s," "${LIST[@]}" | cut -d "," -f 1-${#LIST[@]} )

printf has 'The format string is reused as often as necessary to satisfy the arguments.' in its man pages, so that the concatenations of the strings is documented. Then the trick is to use the LIST length to chop the last sperator, since cut will retain only the lenght of LIST as fields count.

查看更多
君临天下
4楼-- · 2019-01-01 08:25
$ foo=(a "b c" d)
$ bar=$(IFS=, ; echo "${foo[*]}")
$ echo "$bar"
a,b c,d
查看更多
姐姐魅力值爆表
5楼-- · 2019-01-01 08:25

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.

查看更多
笑指拈花
6楼-- · 2019-01-01 08:26

Surprisingly my solution is not yet given :) This is the simplest way for me. It doesn't need a function:

IFS=, eval 'joined="${foo[*]}"'

Note: This solution was observed to work well in non-POSIX mode. In POSIX mode, the elements are still joined properly, but IFS=, becomes permanent.

查看更多
刘海飞了
7楼-- · 2019-01-01 08:26

Right now I'm using:

TO_IGNORE=(
    E201 # Whitespace after '('
    E301 # Expected N blank lines, found M
    E303 # Too many blank lines (pep8 gets confused by comments)
)
ARGS="--ignore `echo ${TO_IGNORE[@]} | tr ' ' ','`"

Which works, but (in the general case) will break horribly if array elements have a space in them.

(For those interested, this is a wrapper script around pep8.py)

查看更多
登录 后发表回答