2

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'
codeforester
  • 39,467
  • 16
  • 112
  • 140
AbhinavVaidya8
  • 522
  • 6
  • 18

2 Answers2

2

Using Bash parameter expansion

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

If you have multiple spaces in the string, then use extended globbing:

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

Using an array

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

Using a loop

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

Related:

codeforester
  • 39,467
  • 16
  • 112
  • 140
0

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'
Hui Zheng
  • 2,394
  • 1
  • 14
  • 18
  • What is your original string? I tried it on `var_list="one two three"` and I did get `'one','two','three'`. What Bash version are you using? – codeforester Jan 30 '21 at 08:01