Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spooling sql to a CSV when data contains commas

I'm trying to spool a sql query to a CSV file using a command prompt, however one column of data I'm returning contains comma's in the data and is causing the data to go into the next column. Is there a way to get around this? Ideally, I would like this particular column returned in the middle of query, not at the end.

I'm currently using the following commands:

set termout off;
set colsep ',';
set underline off;
set feedback off;
set pagesize 0;
set linesize 1500;
set trimspool on;

I know the set colsep ',' command is the issue however, haven't been able to figure out what to replace it with. Does anyone have any recommendations?

Also, right before my sql query, I'm using a select statement to pull the header information. Select 'a, b, c' from dual; Not sure if that makes a difference in the answer or not.

like image 682
user2175401 Avatar asked Mar 15 '13 20:03

user2175401


1 Answers

Two potential answers. Neither of them perfect. If you have commas in some of the results, but no pipes (|), you could switch to a pipe-delimited with

set colsep '|'

Most software that can read csv will do just fine with that format.

If that doesn't work for you, you can realize that to treat commas within a column, you'll need to wrap every data item in quotes:

"data 1","data 2","data,with,commas"

To do this, each separator will need to be "," so you can

set colsep '","'

This will not have quotation marks at the beginning and ending of each line, so you can then wrap every line in quotes with sed:

sed 's/^[^$]*$/"&"/' 
like image 67
Wilduck Avatar answered Sep 24 '22 02:09

Wilduck