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

a 夏天 提交于 2020-07-03 13:32:09

问题


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 line
  • s/ /','/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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!