LoginSignup
1
1

More than 5 years have passed since last update.

psqlコマンドでレコードの値だけをCSV形式で出力させる

Posted at

ペインポイント

  • Ansible等でデータベース上の値だけをさっと取り出したいことがある。
  • しかし他のオプションなしで psql -c "${SQL}" を実行すると下記のような出力になる。。
 pg_encoding_to_char | datcollate 
---------------------+------------
 UTF8                | C
(1 row)

やりかた

psql --no-align --tuples-only -F, -c "${SQL}"

-F,は区切り文字を指定するオプションなので、「|」のままで良ければ不要。

もしくは、一文字オプションを使って

psql -At -F, -c "${SQL}"

e.g.

$ sudo -u postgres psql --no-align --tuples-only -F, -c "select pg_encoding_to_char(encoding), datcollate from pg_catalog.pg_database where datname = 'template1'"
UTF8,C
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1