psql
起動時に-o [ファイル名]
オプションを付けて出力先を指定することで、psqlで実行したクエリの結果をファイルに出力できます。
実行ログ
[postgres@vagrant-centos65 ~]$ /usr/local/pgsql/bin/psql test -q -t -o result.out
test=#
test=#
test=# \qecho hoge fuga piyo
test=# select 1,2,3;
test=# \o
test=# select 4,5,6;
4 | 5 | 6
test=# \q
[postgres@vagrant-centos65 ~]$
[postgres@vagrant-centos65 ~]$
[postgres@vagrant-centos65 ~]$
[postgres@vagrant-centos65 ~]$ cat result.out
hoge fuga piyo
1 | 2 | 3
[postgres@vagrant-centos65 ~]$
各オプション説明
オプション名 |
説明 |
ヘルプ内容 |
-q(--quit) |
メッセージ出力(psql起動時のwelcomeメッセージ等)を省略 |
run quietly (no messages, only query output) |
-t(--tuples-only) |
カラム名と行数フッタ出力を省略 |
print rows only |
-o(--output) [ファイル名] |
クエリ出力結果をファイルにリダイレクト |
send query results to file (or |pipe) |
メタコマンド説明
オプション名 |
説明 |
ヘルプ内容 |
\qecho [出力文言] |
出力文言をファイルに出力 |
write string to query output stream (see \o) |
\o [ファイル名] |
クエリ実行結果をファイルに出力 |
send all query results to file or |pipe |
注意
- psqlプロンプトで
\o
実行後は標準出力に出力されるようになります。
-o
オプション指定時に、psql内で文言出力したい場合は \qecho
を使用すべき。