Redirect Postgresql Select Query to Variable

How to redirect postgresql select query to a variable using shell scripts?

I tried to use

psql -c "select ip from servers" db | egrep '[0-9]+\.[0-9]+\[0-9]+\[0-9]+' | sed 's/^ *\(.*\) *$/\1/'

Output:
10.10.10.180
10.10.10.181

It display ip addresses from the databasem, but how could i redirect the result to an array/how to loop the ip addresses?

Thanks in advance.

Hi,

declare -a array
array=( $(psql -c "select ip from servers" db | egrep '[0-9]+\.[0-9]+\[0-9]+\[0-9]+' | sed 's/^ *\(.*\) *$/\1/') )

You can access the items in the array with:

echo ${array[1]}; echo ${array[2]}; ...

or loop through the array:

for i in ${array[@]}; do echo $i; done

Note: You don't need grep. Sed could do this, too.

HTH Chris

Thanks Chris

Could you tell me how to use sed only?

I tried the sed command but still not success.

You can combine search and replacement in sed. Syntax:

sed -n '/pattern/s/foo/bar/p' file

sed -n -- only print lines when asked to do so
'/pattern/ -- search for pattern
s/foo/bar/ -- if found replace only on this line foo by bar
p -- print lines only if substitution took place.

HTH Chris