comma separated values to single inverted quote an

2020-03-08 08:21发布

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. I used "sed". I have been looking all over internet,but didnot come across a solution. Please help me.

标签: linux bash shell
4条回答
迷人小祖宗
2楼-- · 2020-03-08 08:33
awk '{gsub(/,/,"\47,\47");print "\47"$0"\47"}' file

'abc','defg','hijklm','op','qrs','tuv'
查看更多
【Aperson】
3楼-- · 2020-03-08 08:41

Using awk gsub function. 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'
查看更多
Deceive 欺骗
4楼-- · 2020-03-08 08:46

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)

results in:

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

in awk (maybe a little clumsy), generally better since field parsing is handled natively by 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)

查看更多
我想做一个坏孩纸
5楼-- · 2020-03-08 08:49

another awk

$ awk -F, -v OFS="','" -v q="'" '{$1=q $1; print $0 q}' file
查看更多
登录 后发表回答