问题
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'
回答1:
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'
回答2:
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.
回答3:
$ 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 lines/ /','/g
will replace space with','
回答4:
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'
来源:https://stackoverflow.com/questions/62265095/bash-separate-values-with-commas-then-surround-them-with-quotes-in-variable