逗号分隔的值转换为单引号和逗号分隔的值 [英] comma separated values to single inverted quote and comma separated values
问题描述
我有数据
abc,defg,hijklm,op,qrs,tuv
我希望将此数据转换为
'abc','defg','hijklm','op','qrs','tuv'
我想在Linux中做.我用"sed".我一直在寻找整个Internet,但是没有找到解决方案.请帮助我.
I want to do in linux. I used "sed". I have been looking all over internet,but didnot come across a solution. Please help me.
推荐答案
在开始(^
)处添加单引号&结束($
),并使用sed和3个表达式(使用-e
选项指定它们),用quote-comma-quote替换逗号(就像您所做的那样):
Add a single quote at start (^
) & end ($
), and replace comma by quote-comma-quote (like you did) using sed with 3 expressions (using -e
option to specify them):
echo abc,defg,hijklm,op,qrs,tuv | sed -e "s/^/'/" -e "s/\$/'/" -e "s/,/',\'/g"
(另:用双引号保护单引号)
(also: protect single quotes with double quotes)
导致:
'abc','defg','hijklm','op','qrs','tuv'
(可能有点笨拙),通常更好,因为字段解析由 (打印除最后一个字段外的所有字段加逗号) (print all fields plus comma except for the last one) 这篇关于逗号分隔的值转换为单引号和逗号分隔的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!awk
本机处理:echo abc,defg,hijklm,op,qrs,tuv | awk -F, "{for (i=1;i<=NF-1;i++) printf(\"'%s',\",\$i); printf(\"'%s'\",\$i);}"