Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change output format for MySQL command line results to CSV

I want to get headerless CSV data from the output of a query to MySQL on the command line. I'm running this query on a different machine from the MySQL server, so all those Google answers with "INTO OUTFILE" are no good.

So I run mysql -e "select people, places from things". That outputs stuff that looks kinda like this:

+--------+-------------+ | people | places      | +--------+-------------+ |   Bill | Raleigh, NC | +--------+-------------+ 

Well, that's no good. But hey, look! If I just pipe it to anything, it turns it into a tab-separated list:

people  places Bill    Raleigh, NC 

That's better- at least it's programmatically parseable. But I don't want TSV, I want CSV, and I don't want that header. I can get rid of the header with mysql <stuff> | tail -n +2, but that's a bother I'd like to avoid if MySQL just has a flag to omit it. And I can't just replace all tabs with commas, because that doesn't handle content with commas in it.

So, how can I get MySQL to omit the header and give me data in CSV format?

like image 380
spiffytech Avatar asked Mar 26 '13 14:03

spiffytech


People also ask

How do I export a MySQL database to a CSV file?

Select the table of the database that you want to export and click on the Export tab from the right side. Select the CSV format from the Format drop-down list and click on the Go button. Select the Save File option and press the OK button. The file will be downloaded in the Downloads folder.

How do I store the MySQL query results in a local CSV file?

use the command insert...select to create a "result" table. The ideal scenario whould be to automatically create the fields of this result table, but this is not possible in mysql. create an ODBC connection to the database. use access or excel to extract the data and then save or process in the way you want.


1 Answers

As a partial answer: mysql -N -B -e "select people, places from things"

-N tells it not to print column headers. -B is "batch mode", and uses tabs to separate fields.

If tab separated values won't suffice, see this Stackoverflow Q&A.

like image 197
Jimothy Avatar answered Sep 20 '22 21:09

Jimothy