如何删除CSV文件的列/列,其中单元格值的字符串用双引号括起来

时间:2013-06-19 19:07:24

标签: unix csv cut

如何从CSV文件中删除一个包含逗号分隔值的列,其中包含用双引号括起来的字符串以及介于两者之间的逗号?我有一个包含4行的文件44.csv,包括如下格式的标题:

column1, column2, column3, column 4, column5, column6
12,455,"string with quotes, and with a comma in between",4432,6787,890,88
4432,6787,"another, string with quotes, and with two comma in between",890,88,12,455
11,22,"simple string",77,777,333,22

我需要从文件中删除1,2,3列,所以我使用了下面的cut命令

cut -d"," -f1,2,3 44.csv > 444.csv

我的输出为

column1, column2, column3
12,455,"string with quotes
4432,6787,"another string with quotes
11,22,"simple string"

但我需要输出

column1, column2, column3
12,455,"string with quotes, and with a comma in between"
4432,6787,"another, string with quotes, and with two comma in between"
11,22,"simple string"

非常感谢任何帮助。

由于 Dhruuv。

3 个答案:

答案 0 :(得分:3)

使用GNU awk版本4或更高版本,您可以使用FPAT来定义模式。

gawk '{print $1, $2, $3}' FPAT="([^,]+)|(\"[^\"]+\")" OFS="," 44.csv

测试:

$ gawk '{print $1, $2, $3}' FPAT="([^,]+)|(\"[^\"]+\")" OFS="," mycsv.csv
column1, column2, column3
12,455,"string with quotes, and with a comma in between"
4432,6787,"another, string with quotes, and with two comma in between"
11,22,"simple string"

答案 1 :(得分:1)

我和Dhruuv有同样的问题,jaypal singh提出的解决方案是正确的,但并不适合我的所有情况。 我建议您使用:https://github.com/dbro/csvquote(启用常见的unix特性,如cut,head,tail,以便与包含分隔符和换行符的csv数据一起正常工作)这对我有用。

答案 2 :(得分:0)

你可以通过使用"作为分隔符在这种特殊情况下进行切割,但我强烈反对它 - 即使你可以在这种情况下使它工作,你可能会在以后得到一个带有转义双引号的字符串,例如\"这也会愚弄它。或者,可以引用更多列(这是完全有效的CSV-ism)。

需要更智能的工具!最简单的获取可能是Perl和Text :: CSV模块 - 您几乎肯定安装了Perl,并且根据您的环境安装Text :: CSV作为包,使用CPAN.pm或cpanminus应该直截了当。

相关问题