使用逗号和单引号连接数组元素 - Bash

Concat array elements with comma and single quote - Bash

如何在Bash.

中转换带单引号和逗号的数组元素
arr=("element1" "element2" "element3")
#element1 element2 element3

想要的结果 'element1','element2','element3'

来自 Martin Clayton answer comma seprated values are achieved using IFS

SAVE_IFS="$IFS"
IFS=","
ARRJOIN="${arr[*]}"
IFS="$SAVE_IFS"

echo "$ARRJOIN"
#element1,element2,element3

但是如何给每个元素加上单引号。

[akshay@localhost tmp]$ arr=("element1" "element2" "element3")
[akshay@localhost tmp]$ joined=$(printf ",'%s'" "${arr[@]}")
[akshay@localhost tmp]$ echo ${joined:1}
'element1','element2','element3'

只需使用 sed:

sed -E "s/([[:alnum:]]+)/'&'/g;s/ /,/g" <<< ${arr[@]}

在第一个 sed 命令中,用单引号将所有字母数字字符串括起来,在第二个命令中,用逗号替换空格。