bash - psql 查询文件中的换行符可能吗?

标签 bash psql

我正在运行一个 bash 文件来处理一些 psql 任务。但是,我希望包含查询 (fp_query.txt) 的文本文件接受换行符以增强可读性。目前,我收到此错误:

parse error at end of line

当我维护换行符时。有没有办法让解释器忽略换行符,以便我可以将它们保留在查询文件中?

作为引用,这里是 .sh 文件:

export PGPASSFILE=.pgpass
psql -h [hostname] -d [dbname] -U [user] -f fp_query.txt

这里是 fp_query.txt:

\copy (SELECT created_at::date, COUNT(*)
    FROM ela_snapshots 
    WHERE created_at::date > CURRENT_DATE - 30 
    GROUP BY 1) to 'ELA_comp_tot_daily_sess.csv' with CSV HEADER

最佳答案

问题不是您的查询文件中有换行符,而是您在 \copy 元命令中有换行符。根据the "Meta-Commands" section of the psql documentation for PostgreSQL 9.5 :

Parsing for arguments stops at the end of the line, or when another unquoted backslash is found. An unquoted backslash is taken as the beginning of a new meta-command. The special sequence \\ (two backslashes) marks the end of arguments and continues parsing SQL commands, if any. That way SQL and psql commands can be freely mixed on a line. But in any case, the arguments of a meta-command cannot continue beyond the end of the line.

(强调我的)。如果您在交互式 psql 提示符下运行它,情况同样如此。

一种解决方法可能是 create a temporary function consisting of your query ,并让您的 \copy 元命令运行仅调用该函数的查询。

关于bash - psql 查询文件中的换行符可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34891524/

相关文章:

linux - 将 cron 日志存储在 timedate 文件中

html - Bash 脚本将类附加到 html 文件

postgresql - 从表中的 "last"N 行中获取平均值

bash - 将变量传递给 psql 脚本

python - 如何在具有 60 个功能的 1000 万行数据库上加速 Django 查询聚合?

bash - 使用 Shell 脚本在新文件中打印带有一些文本的日期

ruby-on-rails - rails heroku - 错误代码 H10 bash : bin/rails: No such file or directory

linux - 使用 Bash 检查另一个目录中是否存在相同的文件

python - 来自 psql 和 psycopg2 的 Postgresql session

linux - 恢复插入到 postgres 数据库