从命令 shell 处理 COPY 到 CSV 中的引号

Handling quotes in COPY to CSV from command shell

我正尝试从命令 shell:

运行 此 COPY 查询
COPY products_273 TO '/tmp/products_199.csv' DELIMITER ',' CSV HEADER;

我知道您可以 运行 使用 psql 从命令行查询:

psql -U username -d mydatabase -c 'SELECT * FROM mytable'

但是我怎样才能将两者结合起来呢?以下似乎不起作用,但我不确定 how/if 我需要逃脱。

psql -U username -d mydatabase -c 'COPY products_273 TO '/tmp/products_199.csv' DELIMITER ',' CSV HEADER;'

不要混用'",用"引用查询。

psql -U username -d mydatabase -c "COPY products_273 TO '/tmp/products_199.csv' DELIMITER ',' CSV HEADER;"

最简单的解决方案是(恕我直言)使用此处文档。这也将解决(几乎)您所有的报价问题:

#!bin/sh
psql -U username -d mydatabase <<OMG
  COPY products_273 TO '/tmp/products_199.csv' DELIMITER ',' CSV HEADER;
OMG

假设一个 UNIX(-oid) shell.

如果您不能在 shell 中使用 here document like I suggest dollar quotes for string literals within your SQL command. Replacing the surrounding single quotes with double quotes would turn on variable expansion,如果包含特殊字符,可能会产生副作用:$`(反引号) , 和 \.

psql -U username -d mydatabase -c 'COPY products_273 TO $$/tmp/products_199.csv$$ DELIMITER $$,$$ CSV HEADER;'

在 shell(单引号)中使用完整引号,字符串按原样传递,对任何字符都没有特殊含义。

如果 SQL 字符串中的特殊字符可以被排除或处理得当, 就可以了。

您可以替换每个单引号 (') within带有 '\'' 的完整引号字符串 - 它有效地结束了引号字符串,附加了一个文字 ' 并开始了一个新的完整引号。

psql -U username -d mydatabase -c 'COPY products_273 TO '\''/tmp/products_199.csv'\'' DELIMITER '\'','\'' CSV HEADER;'

相关:

  • How to escape single-quotes within single-quoted strings?

将SQL命令放在单独的文件中(不带引号)并使用psql -f :

psql -U username -d mydatabase -f /path/to/myfile.sql

我假设您知道 \copy (the psql meta-command) and COPY(SQL 命令)之间的区别。 \copy 读取和写入 客户端 的本地文件,而 COPY 服务器 上的文件执行相同的操作。如果客户端和服务器 运行 在同一个安装上,您可以使用其中任何一个。不过,存在某些差异。

  • Problems while importing a txt file into postgres using php