Unix - Surround First Column of CSV with double quotes

2

0

I have data in the following format -

4,"abc"
8,"def"
9,"ghi"

I want to surround the value of the first column by double quotes.

"4","abc"
"8","def"
"9","ghi"

How do I do that ?

Abhinav Manchanda

Posted 2013-10-23T09:32:42.550

Reputation: 135

Answers

6

A very simple substitution is:

cat tmp.csv | awk -F, '{sub($1, "\"&\""); print}'

The option -F, tells awk that the field delimiter is the comma, the argument of sub(stitution) tells awk to replace the first field with itself (&), preceded and followed by ".

MariusMatutiae

Posted 2013-10-23T09:32:42.550

Reputation: 41 321

Useless use of cat, but +1 anyway. – evilsoup – 2013-10-23T10:54:20.817

Right. Should be awk -F, '{sub($1, ""&""); print}' tmp.csv. TY – MariusMatutiae – 2013-10-23T11:00:33.070

0

This is just a quick and dirty way (there will be better ways):

sed -e 's/"//g' -e 's/^\|$/"/g' -e 's/,/","/g' file.csv

The first s/"//g removes all ".
Then s/^\|$/"/g adds a " at the beginning and end of the line.
And last s/,/","/g replaces all , by ",".

Of course this only works if you don't have " and , in your fields.

Rik

Posted 2013-10-23T09:32:42.550

Reputation: 11 800

0

This might work for you (GNU sed):

sed 's/[^,]*/"&"/' file

potong

Posted 2013-10-23T09:32:42.550

Reputation: 141