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:32
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

查看更多
人气声优
3楼-- · 2019-01-01 08:36

printf solution that accept separators of any length (based on @doesn't matters answer)

#/!bin/bash
foo=('foo bar' 'foo baz' 'bar baz')

sep=',' # can be of any length
bar=$(printf "${sep}%s" "${foo[@]}")
bar=${bar:${#sep}}

echo $bar
查看更多
唯独是你
4楼-- · 2019-01-01 08:38
awk -v sep=. 'BEGIN{ORS=OFS="";for(i=1;i<ARGC;i++){print ARGV[i],ARGC-i-1?sep:""}}' "${arr[@]}"

or

$ a=(1 "a b" 3)
$ b=$(IFS=, ; echo "${a[*]}")
$ echo $b
1,a b,3
查看更多
登录 后发表回答