How can I join elements of an array in Bash?

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

    Many, if not most, of these solutions rely on arcane syntax, brain-busting regex tricks, or calls to external executables. I would like to propose a simple, bash-only solution that is very easy to understand, and only slightly sub-optimal, performance-wise.

    join_by () {
        # Argument #1 is the separator. It can be multi-character.
        # Argument #2, 3, and so on, are the elements to be joined.
        # Usage: join_by ", " "${array[@]}"
        local SEPARATOR="$1"
        shift
    
        local F=0
        for x in "$@"
        do
            if [[ F -eq 1 ]]
            then
                echo -n "$SEPARATOR"
            else
                F=1
            fi
            echo -n "$x"
        done
        echo
    }
    

    Example:

    $ a=( 1 "2 2" 3 )
    $ join_by ", " "${a[@]}"
    1, 2 2, 3
    $ 
    

    I'd like to point out that any solution that uses /usr/bin/[ or /usr/bin/printf is inherently slower than my solution, since I use 100% pure bash. As an example of its performance, Here's a demo where I create an array with 1,000,000 random integers, then join them all with a comma, and time it.

    $ eval $(echo -n "a=("; x=0 ; while [[ x -lt 1000000 ]]; do echo -n " $RANDOM" ; x=$((x+1)); done; echo " )")
    $ time join_by , ${a[@]} >/dev/null
    real    0m8.590s
    user    0m8.591s
    sys     0m0.000s
    $ 
    

提交回复
热议问题