6

I currently want to extract a value from a SQL command responde

somehting like this:

psql db -c "SELECT COUNT(test) FROM tbTest;"

the result is:

 count
------
 33176
(1 row)

I want to extract the 33176 value... is there any simple way to do this?

5 Answers 5

28

Why mucking with the unwanted stuff? Simply use some psql options...

> psql -At -c "SELECT COUNT(test) FROM tbTest;" db
115899
Sign up to request clarification or add additional context in comments.

3 Comments

simplify to: psql db -Atc 'SELECT count(test) FROM tbtest'
+1. This is especially useful if you want to select multiple columns, as it removes whitespace.
from PostgreSQL 9.6 onwards, you should also add a -X to suppress execution of an psqlrc file (till 9.5 -c did imply that).
4

If it is always return in that format (expected result on line 3), you can use this:

psql db -c "SELECT COUNT(test) FROM tbTest;" | tail -n 2 | head -n 1

The explanation:

tail -n 2 will get the last 2 line and then processed by head -n 1 which mean, get first 1 line.

1 Comment

A.H. provides a much more elegant solution.
4

By enclosing the complete shell command in backticks, you can retrieve its result into a shell variable:

#/bin/sh

THECOUNT=`psql -A -t -c 'SELECT COUNT(*) FROM tbTest;' db`
echo "the count = $THECOUNT"

Comments

2

Edit: actually, this does not work, sorry. But bellow works.

If the result is always 4 lines, and without invoking any other commands that create a process:

(read; read; read count; read ) < <(psql db -c "SELECT COUNT(test) FROM tbTest;")
echo "$count"

This also work:

End edit

psql db -c "SELECT COUNT(test) FROM tbTest;" | (read; read; read count; read; echo "$count")

Warning: the count variable will not be available out of the parentheses because the pipe (|) launch a new process. So this does not work:

psql db -c "SELECT COUNT(test) FROM tbTest;" | (read; read; read count; read)
echo "$count"

Edit:

If you want count in a variable, you can:

count=$(psql db -c "SELECT COUNT(test) FROM tbTest;" | (read; read; read count_tmp; read; echo "$count_tmp"))

Comments

1

If you can accept to launch a process, but not two (head and tail), you could:

psql db -c "SELECT COUNT(test) FROM tbTest;" | sed -n -e '3p'

This always assume that the output of psql will be 4 lines and you need the 3rd one.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.