How can I join elements of an array in Bash?

前端 未结 30 2138
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 12:05

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.

30条回答
  •  既然无缘
    2020-11-22 12:08

    Yet another solution:

    #!/bin/bash
    foo=('foo bar' 'foo baz' 'bar baz')
    bar=$(printf ",%s" "${foo[@]}")
    bar=${bar:1}
    
    echo $bar
    

    Edit: same but for multi-character variable length separator:

    #!/bin/bash
    separator=")|(" # e.g. constructing regex, pray it does not contain %s
    foo=('foo bar' 'foo baz' 'bar baz')
    regex="$( printf "${separator}%s" "${foo[@]}" )"
    regex="${regex:${#separator}}" # remove leading separator
    echo "${regex}"
    # Prints: foo bar)|(foo baz)|(bar baz
    

提交回复
热议问题