UNIX - 用双引号括住 CSV 的所有列值

UNIX - 用双引号括住 CSV 的所有列值

我有以下格式的数据:

productType , Description
Oven , Accurate Preheat, good start for the day 
hairDryers , Comes with extended warranty , 50% off

期望输出:

"productType" , "Description"
"Oven" , "Accurate Preheat, good start for the day" 
"hairDryers" , "Comes with extended warranty , 50% off"

我使用了以下 SED 命令:

sed -e 's/"//g' -e 's/^\|$/"/g' -e 's/,/","/g' filename.csv

如果您有在单元格值中。

相反,它的结果如下:

"productType","Description"
"Oven","Accurate Preheat"," good start for the day" 
"hairDryers","Comes with extended warranty "," 50% off"

有什么方法可以修复此输出以获得所需的输出?

答案1

尝试:

$ sed -E 's/([^,]*) , (.*)/"\1" , "\2"/' input
"productType" , "Description"
"Oven" , "Accurate Preheat, good start for the day"
"hairDryers" , "Comes with extended warranty , 50% off"

在所有示例中,第一个逗号是字段分隔符,第二个逗号(如果有)是第二个字段的一部分。因此,我们根据第一个逗号在行上的位置来分隔输入,并将两部分放在引号中。

相关内容