我希望通过添加引号来修改包含标题的CSV(逗号分隔文件)的第一行。这是一个非常大的文件,我试图使用AWK来解决这个问题。
在:
id,var1,var2
1,0.11,0.44
2,0.22,0.55
3,0.33,0.66
后:
"id","var1","var2"
1,0.11,0.44
2,0.22,0.55
3,0.33,0.66
像这样的东西,它为所有列添加引号,但对于所有行:
awk -F"," -v quote="'" -v OFS="','" '$1=$1 {print quote $0 quote}' input.csv > output.csv
我只想在第一行附近引用。我试图使用NR,但无法使语法正确以做我想要的。
答案 0 :(得分:2)
你可以使用这个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
编辑:如果您想在标题中加双引号,请使用:
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
答案 1 :(得分:2)
如果您可以访问GNU sed:
sed '1s/\b\w*\b/"&"/g' file
输出:
"id" "var1" "var2" 1 0.11 0.44 2 0.22 0.55 3 0.33 0.66
答案 2 :(得分:2)
$ 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