How to add quotation marks to fields in a CSV file?

I have a CSV file like

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

I would like to add quotation marks so that it is like this:

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

What is the fastest way to do this? I will implement this in a cronjob.

+4
source share
4 answers

Using sed:

 sed -e 's/^\|$/"/g' -e 's/,/","/g' input 
+7
source

This may work for you (GNU sed):

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

With awk :

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

It is often not recommended to use a language with a CSV library for CSV data:

 ruby -rcsv -ne 'puts CSV.generate_line(CSV.parse_line($_), :force_quotes=>true)' 
+1
source

Source: https://habr.com/ru/post/1486720/


All Articles