postgresql - Postgres COPY 命令 - 带逗号的字段,用双引号引起来

标签 postgresql csv copy

我搜索并找到了一些与 postgres csv 导入相关的帖子,但没有任何内容可以解决我当前的问题。

我一直使用 postgres copy 命令将异构数据源中的数据导入我们的系统。目前正在努力处理 1 亿行的 .csv 文件,逗号分隔。问题在于这样的行:

009098,0981098094,"something","something else",""this one, well, is a problem"", "another thing"

用双引号括起来的字段,内嵌逗号。字段未正确解析,我收到错误:

"ERROR:  extra data after last expected column" 

通常出现这种情况时,我会临时处理有问题的行,但是这个文件太大了,我希望有一些更通用的方法来防御它。要求修改数据格式是不可能的。

copy mytable from '/path/to/file.csv' csv header quote '"'

最佳答案

这是格式错误的 CSV。您将双引号加倍以在引号字段中嵌入双引号;例如:

"where","is ""pancakes""","house?"

具有三个值:

  • 哪里
  • 是“煎饼”
  • 房子?

您遇到问题的行有杂散的双引号:

009098,0981098094,"something","something else",""this one, well, is a problem"", "another thing"
                                               ^^                            ^^ 

我不认为有什么 COPY可以这样做,因为正确的版本是模棱两可的:它应该是 "this one, well, is a problem" 还是应该是 """this one, well, is a problem"""?

我认为您必须手动修复它。如果您可以唯一地识别损坏的行,一个快速的 sed 单行程序应该能够完成这项工作。


作为引用,我见过的最接近 CSV 标准的是 RFC 4180第二部分是这样说的:

5.  Each field may or may not be enclosed in double quotes (however
    some programs, such as Microsoft Excel, do not use double quotes
    at all).  If fields are not enclosed with double quotes, then
    double quotes may not appear inside the fields.  For example:

    "aaa","bbb","ccc" CRLF
     zzz,yyy,xxx
[...]
7.  If double-quotes are used to enclose fields, then a double-quote
    appearing inside a field must be escaped by preceding it with
    another double quote.  For example:

    "aaa","b""bb","ccc"

关于postgresql - Postgres COPY 命令 - 带逗号的字段,用双引号引起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13183644/

相关文章:

postgresql - 将记录分组 - 快速解决方案

postgresql - 如何将 NEW/OLD 传递给从 PostgreSQL 中的触发器函数调用的过程?

java - 追加到文件中行的末尾

javascript - 从 HTML 网站查询或搜索 CSV 的最佳方式

c++ - 如果目录不存在则创建目录

mysql - postgres 按错误分组

mysql - 哪些是最小化服务器往返的 RDBMS?哪个 RDBMS(在这方面)比 MS SQL 更好?

php - 使用 php 创建 csv 文件时出现希伯来语问题

c++ - 折叠复制和 move 语义的重载

c# - 复制 .svn 文件?