9

How can I concatenate two psql (PostgreSQL client) variables? I want to generate an absolute path by concatenating a directory path variable and a filename variable.

I've tried this:

\set path '/tmp/'
\set file 'foo'
\echo :path:file

But psql puts a space between the path and the file, and outputs:

/tmp/ foo
Erwin Brandstetter
  • 175,982
  • 27
  • 439
  • 600
Daniel Serodio
  • 1,249
  • 3
  • 12
  • 13

3 Answers3

10
\set path '/tmp/'
\set file 'foo'
\set pf :path:file \echo :pf
/tmp/foo

Why does this work? I quote the manual here:

\set [ name [ value [ ... ] ] ]

Sets the internal variable name to value or, if more than one value is given, to the concatenation of all of them. [...]

Emphasis mine.

Erwin Brandstetter
  • 175,982
  • 27
  • 439
  • 600
4

Try this:

\set path /tmp/
\set file foo
\qecho :path:file \o | sed s/\ //
/tmp/foo

\qecho writes to the query output channel (unlike \echo, which writes to standard output). \o | then redirects the output to the subsequent command.

András Váczi
  • 31,278
  • 13
  • 101
  • 147
0

It looks like you want either the || operator or the concat function:

http://www.postgresql.org/docs/9.1/static/functions-string.html

Cargo23
  • 249
  • 1
  • 4