【发布时间】:2018-11-28 15:05:11
【问题描述】:
我的变量中有几个参数。我想用单引号替换每个变量,用逗号分隔。
var_list=emp location branch.
我希望我的输出如下:
var_list='emp', 'location', 'branch'
【问题讨论】:
我的变量中有几个参数。我想用单引号替换每个变量,用逗号分隔。
var_list=emp location branch.
我希望我的输出如下:
var_list='emp', 'location', 'branch'
【问题讨论】:
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 我尝试了第一种方法
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 版本?