vkrishna vkrishna - 1 year ago 69
Bash Question

comma separated values to single inverted quote and comma separated values

I have data as


I want this data to be converted to


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.

Answer Source

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:


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)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download