MySQL query to print output as CSV to standard output

Blaine Lafreniere picture Blaine Lafreniere · Oct 16, 2010 · Viewed 8.9k times · Source

I want to do the following mysql -uuser -ppass -h remote.host.tld database < script.sql

where script.sql contains the following

SELECT *
FROM webrecord_wr25mfz_20101011_175524
FIELDS TERMINATED BY ',' 
ENCLOSED BY '"' 
LINES TERMINATED BY '\n'

I want CSV output directed to standard out. The reason is because running this query with an INTO OUTFILE 'blah.csv' will save the file on the remote host. I want the file saved on the local host.

If I could just redirect the standard output to a file, that would be dandy.

Answer

instaflow picture instaflow · Jul 14, 2019

In part a duplicate question to MySQL SELECT INTO OUTFILE to a different server. FIELDS TERMINATED BY can't be used without into outfile

A (not so elegant) alternative is using the --batch option to produce tab separated output and sedding the stdout. Something like this:

mysql --batch -uuser -ppass -h remote.host.tld database < stack.sql | sed 's/\t/,/g' > blah.csv

Be aware that --batch escapes special characters so depending on the data you have and its predictability, you might need to change the sed