简体   繁体   English

逗号分隔的值转换为单引号和逗号分隔的值

[英]comma separated values to single inverted quote and comma separated values

I have data as 我有数据

    abc,defg,hijklm,op,qrs,tuv

I want this data to be converted to 我希望将这些数据转换为

    'abc','defg','hijklm','op','qrs','tuv'

I want to do in linux. 我想在linux中做。 I used "sed". 我用“ sed”。 I have been looking all over internet,but didnot come across a solution. 我一直在寻找整个Internet,但是没有找到解决方案。 Please help me. 请帮我。

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): 在开始( ^ )和结束( $ )处添加一个单引号,并使用sed和3个表达式(使用-e选项指定它们),用quote-comma-quote替换逗号(就像您所做的那样):

echo  abc,defg,hijklm,op,qrs,tuv | sed -e "s/^/'/" -e "s/\$/'/" -e "s/,/',\'/g" 

(also: protect single quotes with double quotes) (另:用双引号保护单引号)

results in: 结果是:

'abc','defg','hijklm','op','qrs','tuv'

in awk (maybe a little clumsy), generally better since field parsing is handled natively by awk : awk (可能有点笨拙),通常更好,因为字段解析是由awk本机处理的:

echo  abc,defg,hijklm,op,qrs,tuv | awk -F, "{for (i=1;i<=NF-1;i++) printf(\"'%s',\",\$i); printf(\"'%s'\",\$i);}"

(print all fields plus comma except for the last one) (打印除最后一个字段外的所有字段加逗号)

Using awk gsub function. 使用awk gsub函数。 Here all the " , " are replaced by ',' and start and the end of the line is replaced by " ' ". 这里所有的“ ”被取代, ','并开始和该行的端改为“ ' ”。

echo $x |awk -v q="'" '{gsub(/,/, q "&" q);gsub(/^|$/,q)}1'
'abc','defg','hijklm','op','qrs','tuv'
awk '{gsub(/,/,"\47,\47");print "\47"$0"\47"}' file

'abc','defg','hijklm','op','qrs','tuv'

另一个awk

$ awk -F, -v OFS="','" -v q="'" '{$1=q $1; print $0 q}' file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM