【问题标题】:Concat array elements with comma and single quote - Bash用逗号和单引号连接数组元素 - Bash
【发布时间】:2018-01-29 12:11:34
【问题描述】:

如何在 Bash 中用单引号和逗号转换数组元素。

arr=("element1" "element2" "element3")
#element1 element2 element3

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

来自Martin Clayton的答案逗号分隔值是使用IFS实现的,

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

echo "$ARRJOIN"
#element1,element2,element3

但是如何为每个元素添加单引号。

【问题讨论】:

    标签: arrays bash ifs


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

    【讨论】:

    • 为什么是 ${joined:1} 而不仅仅是 ${joined}?或者: :1 是做什么的?
    • 啊,它删除了第一个字符。当然,连接最后会产生一个额外的逗号。
    【解决方案2】:

    只需使用 sed:

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

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

    【讨论】:

    • 如果任何元素包含非字母数字字符(空格、标点符号等),这将无法正常工作。
    猜你喜欢
    • 2022-01-16
    • 1970-01-01
    • 2018-06-19
    • 1970-01-01
    • 2011-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多