I Have a couple of arguments in my variable. I want to replace each variable with single quotes, separated by a comma.
var_list=emp location branch.
I want my output like:
var_list='emp', 'location', 'branch'
I Have a couple of arguments in my variable. I want to replace each variable with single quotes, separated by a comma.
var_list=emp location branch.
I want my output like:
var_list='emp', 'location', 'branch'
delimited="'${var_list//[[:space:]]/"','"}'"
If you have multiple spaces in the string, then use extended globbing:
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
Related:
Thank you @codeforester I tried the first approach
delimited="'${var_list//[[:space:]]/"','"}'"
but it doesn't work. I got
'word_1"', '"word_2"', '"word_3'
Then I revised to statement to
delimited="'${var_list//[[:space:]]/','}'"
It works correctly.
'word_1', 'word_2', 'word_3'