First of all, Steffen's answer works in most cases.
I recently encountered some larger and more complex outputs where "sed" was not enough and decided to come up with a simple utility to do exactly that.
I build a module called sql2csv that can parse the output of the MySQL CLI:
$ mysql my_db -e "SELECT * FROM some_mysql_table"
+----+----------+-------------+---------------------+
| id | some_int | some_str | some_date |
+----+----------+-------------+---------------------+
| 1 | 12 | hello world | 2018-12-01 12:23:12 |
| 2 | 15 | hello | 2018-12-05 12:18:12 |
| 3 | 18 | world | 2018-12-08 12:17:12 |
+----+----------+-------------+---------------------+
$ mysql my_db -e "SELECT * FROM some_mysql_table" | sql2csv
id,some_int,some_str,some_date
1,12,hello world,2018-12-01 12:23:12
2,15,hello,2018-12-05 12:18:12
3,18,world,2018-12-08 12:17:12
You can also use the built in CLI:
sql2csv -u root -p "secret" -d my_db --query "SELECT * FROM some_mysql_table;"
1,12,hello world,2018-12-01 12:23:12
2,15,hello,2018-12-05 12:18:12
3,18,world,2018-12-08 12:17:12
More information in on sql2csv (GitHub).
mysql
's--batch
flag outputs tab-separated fields, with the contents escaped. This is a common format and should not require translation to .csv, which when done withsed
could potentially result in mangled data in corner cases.mysql db -e 'query' > out.tsv
will output a TSV output while the same command without redirection will print a tabular output.