B.T Anand
B.T Anand

Reputation: 607

Bash Separate values with commas then surround them with quotes in variable

I have the below bash script:

STR1="US-1234 US-7685 TKT-008953"
#STR2= "${STR1// /,}"
STR2=`echo $STR1 | sed 's/ /,/g'`
echo $STR2

Current output: US-1234,US-7685,TKT-008953

Expected output: 'US-1234','US-9754','TKT-007643'

Upvotes: 0

Views: 2154

Answers (4)

James Brown
James Brown

Reputation: 37394

Use bash's global variable replacement to replace space with ',' and add quotes around it:

$ str2=\'${str1// /\',\'}\'
$ echo $str2
'US-1234','US-7685','TKT-008953'

Upvotes: 0

Cyrus
Cyrus

Reputation: 88583

With bash and its parameter expansion:

STR1="US-1234 US-7685 TKT-008953"
STR1="${STR1// /\',\'}"
STR1="${STR1/#/\'}"
echo "${STR1/%/\'}"

Output:

'US-1234','US-7685','TKT-008953'

Upvotes: 4

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You may use

STR2="'$(echo "$STR1" | sed "s/ /','/g")'"

See online demo

All spaces are replaced with ',' using sed "s/ /','/g", and the initial and trailing single quotes are added inside a double quoted string.

Upvotes: 2

Sundeep
Sundeep

Reputation: 23667

$ echo 'US-1234 US-7685 TKT-008953' | sed -E "s/^|$/'/g; s/ /','/g"
'US-1234','US-7685','TKT-008953'

$ # can also use \x27 and continue using single quotes for the expression
$ echo 'US-1234 US-7685 TKT-008953' | sed -E 's/^|$/\x27/g; s/ /\x27,\x27/g'
'US-1234','US-7685','TKT-008953'
  • s/^|$/'/g will add single quote at start/end of line
  • s/ /','/g will replace space with ','

Upvotes: 0

Related Questions