SharkSandwich
SharkSandwich

Reputation: 299

Add quotes to first line of CSV

I wish to modify the first row of a CSV (comma-separated file) which contains headings by adding quotes. It's a very large file, I was trying to use AWK for this problem.

Before:

id,var1,var2
1,0.11,0.44
2,0.22,0.55
3,0.33,0.66

After:

"id","var1","var2"
1,0.11,0.44
2,0.22,0.55
3,0.33,0.66

Something like this, which adds quotes for all columns, but for all rows:

awk -F"," -v quote="'" -v OFS="','" '$1=$1 {print quote $0 quote}' input.csv > output.csv

I just want quotes around the first line. I was trying to use NR, but couldn't get the syntax correct to do what I wanted.

Upvotes: 1

Views: 164

Answers (3)

anubhava
anubhava

Reputation: 786289

You can use this awk:

awk 'BEGIN{FS=OFS=","} NR==1{for (i=1; i<=NF; i++) $i = "\047" $i "\047"} 1' file
'id','var1','var2'
1,0.11,0.44
2,0.22,0.55
3,0.33,0.66

EDIT: If you wanted double quotes in headers then use:

awk 'BEGIN{FS=OFS=","} NR==1{for (i=1; i<=NF; i++) $i = "\042" $i "\042"} 1' file
"id","var1","var2"
1,0.11,0.44
2,0.22,0.55
3,0.33,0.66

Upvotes: 2

Ed Morton
Ed Morton

Reputation: 204638

$ awk 'NR==1{gsub(/,/,"\",\""); $0="\""$0"\""} 1' file
"id","var1","var2"
1,0.11,0.44
2,0.22,0.55
3,0.33,0.66

Upvotes: 2

Cyrus
Cyrus

Reputation: 88999

If you have access to GNU sed:

sed '1s/\b\w*\b/"&"/g' file

Output:

"id" "var1" "var2"
1 0.11 0.44
2 0.22 0.55
3 0.33 0.66

Upvotes: 2

Related Questions