将 psql 输出保存到 csv 文件

Saving psql output to csv file

我在 /path/to/query 的文件中写了一个查询。如何在不在查询中使用 COPY 的情况下将输出结果保存到 csv 文件?我尝试了以下命令,但输出文件的字段由“|”分隔。

psql -U username -d dbname -f /path/to/query -o /path/to/output/file -F ','

文档中没有解释,但是-F选项需要-A选项(未对齐的table输出)才能工作:

psql -U username -d dbname -f /path/to/query -o /path/to/output/file -F ',' -A

如果您不希望在您的 csv 中使用 headers,这意味着顶部和底部没有额外的行,也可以使用 -t 选项。

psql -U username -d dbname -f /path/to/query -o /path/to/output/file -F ',' -A -t

来自帮助:

-A, --no-align unaligned table output mode
-F, --field-separator=STRING set field separator (default: "|")
-t, --tuples-only print rows only