How can I join elements of an array in Bash?

前端 未结 30 2153
爱一瞬间的悲伤
爱一瞬间的悲伤 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:31
    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

    0 讨论(0)
  • 2020-11-22 12:32

    Here's one that most POSIX compatible shells support:

    join_by() {
        # Usage:  join_by "||" a b c d
        local arg arr=() sep="$1"
        shift
        for arg in "$@"; do
            if [ 0 -lt "${#arr[@]}" ]; then
                arr+=("${sep}")
            fi
            arr+=("${arg}") || break
        done
        printf "%s" "${arr[@]}"
    }
    
    0 讨论(0)
  • 2020-11-22 12:33

    I would echo the array as a string, then transform the spaces into line feeds, and then use paste to join everything in one line like so:

    tr " " "\n" <<< "$FOO" | paste -sd , -

    Results:

    a,b,c

    This seems to be the quickest and cleanest to me !

    0 讨论(0)
  • 2020-11-22 12:34

    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.

    0 讨论(0)
  • 2020-11-22 12:34

    Here's a single liner that is a bit weird but works well for multi-character delimiters and supports any value (including containing spaces or anything):

    ar=(abc "foo bar" 456)
    delim=" | "
    printf "%s\n$delim\n" "${ar[@]}" | head -n-1 | paste -sd ''
    

    This would show in the console as

    abc | foo bar | 456
    

    Note: Notice how some solutions use printf with ${ar[*]} and some with ${ar[@]}? The later ones (with @) use the printf feature that support multiple arguments by repeating the format template, while the former ones do not actually need printf and rely on manipulating the field separator and bash's word expansion and would work just as well with echo, cat and others - these solutions likely use printf because the author doesn't really understand what they are doing, and you should not use them.

    0 讨论(0)
  • 2020-11-22 12:35

    My attempt.

    $ array=(one two "three four" five)
    $ echo "${array[0]}$(printf " SEP %s" "${array[@]:1}")"
    one SEP two SEP three four SEP five
    
    0 讨论(0)
提交回复
热议问题