【问题标题】:How to delete a column/columns of a CSV file which has cell values with a string enclosed in double quotes如何删除 CSV 文件的列/列,该文件的单元格值带有用双引号括起来的字符串
【发布时间】:2013-06-19 19:07:24
【问题描述】:

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

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 -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"

非常感谢任何帮助。

谢谢 德鲁夫。

【问题讨论】:

  • Cut 在这里帮不了你。我会考虑使用具有真正 csv 支持的编程语言,例如蟒蛇。
  • 您的文件 44.csv 是否总是有 4 行?如果是这样,4行根本不算多。我会手动清理它。
  • 不,它在每个文件中有超过 400-500 行,我必须在每个文件中这样做。以上只是理解我的问题的一个示例。

标签: unix csv cut


【解决方案1】:

对于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"

【讨论】:

  • 我的是 GNU Awk 3.1.5。我怎样才能做到这一点。因为你的代码我得到的输出为 column1, column2, column3, 12,455,"string with quotes, 4432,6787,"another, string with 11,22,"simple string",77,777,333,22
  • 它不适用于GNU awk 3.1.5。 FPAT 在版本 4 中引入。
  • 还有其他建议吗?
  • 我不确定,因为我是 Linux 新手,不知道是否已安装...我正在尝试检查。
  • 我是在命令行执行的:perl -v 输出:这是 perl, v5.8.8 built for x86_64-linux-thread-multi............ 这意味着我已经安装了 perl...上述问题的任何替代解决方案?
【解决方案2】:

我遇到了与 Dhruuv 相同的问题,jaypal singh 提出的解决方案是正确的,但不适用于我的所有情况。 我建议您使用:https://github.com/dbro/csvquote(使常见的 unix 实用程序(如 cut、head、tail)能够正确处理包含分隔符和换行符的 csv 数据)这对我有用。

【讨论】:

    【解决方案3】:

    在这种特殊情况下,您可以通过使用 " 作为分隔符来执行此操作,但我强烈建议您不要这样做——即使您可以在这种情况下使其工作,您稍后可能会得到一个带有转义双引号的字符串,例如\" 这也会愚弄。或者,您的更多列可能会被引用(这是完全有效的 CSV 主义)。

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

    【讨论】:

      猜你喜欢
      • 2011-02-14
      • 2021-06-02
      • 1970-01-01
      • 2020-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-11
      相关资源
      最近更新 更多