如何指定要在SQLite输出中使用的记录分隔符?

时间:2014-10-18 09:24:56

标签: sql sqlite

我使用以下命令将SQL查询的结果输出到文本文件:

$sqlite3 my_db.sqlite "SELECT text FROM message;" > out.txt

这给了我这样的输出:

text for entry 1
text for entry 2

不幸的是,当文本包含换行符时,这会中断:

text for entry 1
text for 
entry 2

如何指定SQLite在输出数据时使用的输出分隔符(我知道文本中不存在),以便我可以更轻松地解析结果? E.g:

text for entry 1
=%=
text for 
entry 2
=%=
text for entry 3

3 个答案:

答案 0 :(得分:4)

请尝试-separator option

$sqlite3 -separator '=%=' my_db.sqlite "SELECT text FROM message;" > out.txt

更新1

我认为这是因为' -list'默认选项。要关闭此选项,您需要更改当前模式。

这是模式列表

.mode MODE ?TABLE?     Set output mode where MODE is one of:
                            csv      Comma-separated values
                            column   Left-aligned columns.  (See .width)
                            html     HTML <table> code
                            insert   SQL insert statements for TABLE
                            line     One value per line
                            list     Values delimited by .separator string
                            tabs     Tab-separated values
                            tcl      TCL list elements


 -list  Query results will  be  displayed  with  the  separator  (|,  by
        default) character between each field value.  The default.

 -separator separator
        Set output field separator.  Default is '|'.

找到此信息here

答案 1 :(得分:3)

我有同样的问题,有一个更简单的解决方案。我在https://sqlite.org/cli.html上找到了它:

.separator COL?ROW?更改列和行分隔符

例如:

    sqlite> .separator | ,
    sqlite> select * from example_table;

1|3,1|4,1|15,1|21,1|33,2|13,2|16,2|32,

或者没有列分隔符:

    sqlite> .separator '' ,
    sqlite> select * from example_table;

13,14,115,121,133,213,216,232,

或者,要回答上面提出的特定问题,这就是所需要的:

    sqlite> .separator '' \r\n=%=\r\n
    sqlite> select * from message;

text for entry 1
=%=
text for
entry 2
=%=
text for entry 3
=%=

答案 2 :(得分:0)

要分隔列,您必须使用group_concat和分隔符。

查询进化:

SELECT text FROM messages;

SELECT GROUP_CONCAT(text, "=%=") FROM messages;

SELECT GROUP_CONCAT(text, "\r\n=%=\r\n") FROM messages;

// to get rid of the concat comma, use replace OR change seperator
SELECT REPLACE(GROUP_CONCAT(text, "\r\n=%="), ',', '\r\n') FROM messages;

<强> SQLFiddle

替代方案:Sqlite到CSV导出(使用自定义分隔符),然后使用它。