Export a postgresql query into csv file

# su -c "psql -d maillog -c \"copy (select date,sender,destination,subject from maillog where destination like '%domain.com%') to '/tmp/mails.csv' with csv;\" " postgres
This command will "su" the execution of the command to the postgres user(implies that you are already logger as root), and export the result of the query to a file on the csv format. You'll need to adequate the fields and database information to one of your choice/need.
Sample Output
head -3 /tmp/mails.csv

2012-09-24 10:00:11.470321,sender@domainsender.com,"dest1@domain.com, dest2@domain.com",Alert:one host is down
2012-09-24 10:45:10.920158,sender@domainsender.com,"dest1@domain.com, dest2@domain.com",Alert:three hosts are down
2012-09-24 10:50:03.736794,sender@domainsender.com,"dest1@domain.com, dest2@domain.com",Alert:one host is down

0
By: Risthel
2013-02-13 13:03:17

What do you think?

Any thoughts on this command? Does it work on your machine? Can you do the same thing with only 14 characters?

You must be signed in to comment.

What's this?

commandlinefu.com is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.

Share Your Commands



Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.

» http://twitter.com/commandlinefu
» http://twitter.com/commandlinefu3
» http://twitter.com/commandlinefu10

Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for: