psql 非选择:如何删除格式并仅显示某些列?

Ste*_*ige 4 postgresql pgpool psql

我希望从以下位置删除所有线描字符:

PGPASSWORD="..." psql -d postgres -h "1.2.3.4" -p 9432 -c 'show pool_nodes' -U owner
 node_id |   hostname    | port | status | lb_weight |  role   
---------+---------------+------+--------+-----------+---------
 0       | 10.20.30.40   | 5432 | 2      | 0.500000  | primary
 1       | 10.20.30.41   | 5432 | 2      | 0.500000  | standby
(2 rows)
Run Code Online (Sandbox Code Playgroud)

添加该-t选项可以去掉页眉和页脚,但竖线仍然存在:

PGPASSWORD="..." psql -t -d postgres -h "1.2.3.4" -p 9432 -c 'show pool_nodes' -U owner
 0       | 10.20.30.40   | 5432 | 2      | 0.500000  | primary
 1       | 10.20.30.41   | 5432 | 2      | 0.500000  | standby
Run Code Online (Sandbox Code Playgroud)

请注意,此问题特定于show pool_nodes和其他类似的非selectSQL 语句。

我目前的解决方法是使用 Linuxcut命令:

<previous command> | cut -d '|' -f 4
Run Code Online (Sandbox Code Playgroud)

问题有两部分:

  1. 怎么用psql只能去掉上面的竖线?
  2. 如何使用psqlonly 只能显示特定的列(例如,status)?例如,结果可能只有两行,每行都显示数字2。

我在psql (PostgreSQL) 9.2.18CentOS 7 服务器上使用 psql 版本。

Cra*_*ger 7

对于脚本psql使用psql -qAtX:

  • q悦
  • t仅限单身
  • 未连接A输出
  • 不读.psqlrc(X)

要过滤列,您必须在SELECT列表中命名它们。psql始终输出它从服务器获得的完整结果集。例如SELECT status FROM pool_nodes。

或者您可以cut提取序数列号,例如

psql -qAtX -c 'whatever' | cut -d '|' -f 1,2-4
Run Code Online (Sandbox Code Playgroud)

(我不知道如何show pool_nodes产生您在此处显示的输出,因为SHOW返回单个标量值...)

要将分隔符从管道更改|为其他内容,请使用-Feg -F ','。但请注意,分隔符出现在输出中时不会转义,这不是 CSV。您可能希望将选项卡视为有用的选项;您必须输入带引号的文字选项卡才能执行此操作。(如果在交互式 shell 中执行此操作,请在遇到问题时搜索“如何在 bash 中输入文字选项卡”)。

给定虚拟数据的示例显示了上述所有内容:

CREATE TABLE dummy_table (
   a integer,
   b integer,
   c text,
   d text
);

INSERT INTO dummy_table
VALUES
(1,1,'chicken','turkey'),
(2,2,'goat','cow'),
(3,3,'mantis','cricket');
Run Code Online (Sandbox Code Playgroud)

查询,以单个空格作为列分隔符(因此您最好不要在数据中包含空格!):

psql -qAtX -F ' ' -c 'SELECT a, b, d FROM dummy_table'
Run Code Online (Sandbox Code Playgroud)

如果由于某种原因您无法为 SELECT 生成列列表,您可以改为按列顺序过滤cut:

psql -qAtX -F '^' -c 'TABLE dummy_table' | cut -d '^' -f 1-2,4
Run Code Online (Sandbox Code Playgroud)