'How can I add quotation marks to fields in a CSV file?

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.



Solution 1:[1]

This might work for you (GNU sed):

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

Solution 2:[2]

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)'

Solution 3:[3]

With awk:

awk '{gsub(/[^,]+/,"\"&\"")}1' file.csv

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 potong
Solution 2 glenn jackman
Solution 3 jaypal singh