如何从命令行以CSV或TSV格式打印PostgreSQL查询的结果? [英] How do you print the result of a PostgreSQL query in CSV or TSV format from the command line?

查看:72
本文介绍了如何从命令行以CSV或TSV格式打印PostgreSQL查询的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从外壳程序(不在交互式psql客户端中)执行查询,并让它将输出的CSV或TSV表示形式输出到STDOUT。您如何使用 psql 或PostgreSQL命令行工具之一来做到这一点?

I'd like to execute a query from the shell (not in the interactive psql client) and have it print the CSV or TSV representation of the output to STDOUT. How do you do that with psql or one of the PostgreSQL command-line tools?

推荐答案

如果您使用的是PostgreSQL 8.2或更高版本,请将其用于CSV:

If you are using PostgreSQL 8.2 or newer, use this for CSV:

psql -c "COPY (<select query>) TO STDOUT WITH CSV"

以及TSV,并带有适当的NULL:

and this of TSV, with proper NULLs:

psql -c "COPY (<select query>) TO STDOUT WITH NULL AS ''"

CSV表单将正确引用任何包含双引号字符的字段。有关COPY的更多详细信息和选项,请参见特定版本的PostgreSQL文档。

The CSV form will properly quote any fields that contain the double-quote character. See the PostgreSQL documentation of your specific version for more details and options for COPY.

这篇关于如何从命令行以CSV或TSV格式打印PostgreSQL查询的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆