7

I've got a CSV file like

Brand,Type,Color
Porsche,Sport,Red
BMW,Coupe,Blue

I'd like to include quotation marks to have it like:

"Brand","Type","Color"
"Porsche","Sport","Red"
"BMW","Coupe","Blue"

What's the fastest way to do it? I will implement it in a cronjob.

pppery
  • 3,731
  • 22
  • 33
  • 46
Adam Lesniak
  • 878
  • 10
  • 32

4 Answers4

9

Using sed:

sed -e 's/^\|$/"/g' -e 's/,/","/g' input
perreal
  • 94,503
  • 21
  • 155
  • 181
  • Note that this will mishandle any commas that appear within double quotes in the input file. It will also mishandle any values that are already double-quoted. In other words, it only works correctly if every value in the input file is unquoted. – John Karahalis May 03 '23 at 19:20
4

It's often neater to use a language with a CSV library for CSV data:

ruby -rcsv -ne 'puts CSV.generate_line(CSV.parse_line($_), :force_quotes=>true)'
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • 1
    This is actually neat! It takes care of those cases 9as I had) where some fields were quoted and some were not. – SACHIN GARG Jan 07 '16 at 00:50
4

This might work for you (GNU sed):

sed -r 's/[^,]+/"&"/g' file

Accounting for the presence of "'s and escaped characters.

sed -E 's/[^\,"]*(("|[\].)[^"\,]*)*/"&"/g' file
potong
  • 55,640
  • 6
  • 51
  • 83
  • Note that this will mishandle any commas that appear within double quotes in the input file. It will also mishandle any values that are already double-quoted. In other words, it only works correctly if every value in the input file is unquoted. – John Karahalis May 03 '23 at 19:25
  • @JohnKarahalis if double quotes were to appear in the field I guess they would need to be escaped (otherwise it would be hard to reverse the required change). However a solution which takes this in mind might look like the above. – potong May 04 '23 at 09:55
3

With awk:

awk '{gsub(/[^,]+/,"\"&\"")}1' file.csv
jaypal singh
  • 74,723
  • 23
  • 102
  • 147
  • Note that this will mishandle any commas that appear within double quotes in the input file. It will also mishandle any values that are already double-quoted. In other words, it only works correctly if every value in the input file is unquoted. – John Karahalis May 03 '23 at 19:25