【问题标题】:How to add single quotes to every word in a string如何为字符串中的每个单词添加单引号
【发布时间】:2018-11-28 15:05:11
【问题描述】:

我的变量中有几个参数。我想用单引号替换每个变量,用逗号分隔。

var_list=emp location  branch.

我希望我的输出如下:

var_list='emp', 'location',  'branch'

【问题讨论】:

    标签: bash shell unix csv


    【解决方案1】:

    使用 Bash 参数扩展

    delimited="'${var_list//[[:space:]]/"','"}'"
    

    如果字符串中有多个空格,则使用扩展通配符:

    shopt -s extglob
    delimited="'${var_list//+([[:space:]])/"','"}'"
    

    使用数组

    words=($var_list)                           # create array from string, using word splitting
    printf -v delimited ",'%s'" "${words[@]}"   # yields ",'one','two',..."
    delimited=${delimited:1}                    # remove the leading ','
    

    使用循环

    delim=''
    for word in $var_list; do                   # rely on word splitting by shell
      delimited="$delimited$delim'$word'"
      delim=","
    done
    

    相关:

    【讨论】:

    • 谢谢,@codeforester,我正在使用 Bash shell,两种方法都试过了,它解决了我的问题。
    • 我使用 Bash shell,我不知道为什么第一种方法不适合我。
    【解决方案2】:

    谢谢@codeforester 我尝试了第一种方法

    delimited="'${var_list//[[:space:]]/"','"}'"
    

    但它不起作用。我得到了

    'word_1"', '"word_2"', '"word_3'
    

    然后我修改为声明为

    delimited="'${var_list//[[:space:]]/','}'"
    

    它工作正常。

    'word_1', 'word_2', 'word_3'
    

    【讨论】:

    • 你的原始字符串是什么?我在var_list="one two three" 上尝试过,我确实得到了'one','two','three'。您使用的是哪个 Bash 版本?
    猜你喜欢
    • 2016-03-10
    • 1970-01-01
    • 2017-01-04
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    • 2016-02-03
    • 2017-07-25
    • 2011-01-13
    相关资源
    最近更新 更多