1

I know I can open a SpatiaLite database and export a CSV from it as the following:

.headers on
.mode csv
.output csvFile.csv
select * from table
.output stdout

However, I'd like to automate the process of exporting CSV files from SpatiaLite with a bash script. Is there any way to execute this same sequence of commands from a shell? Just so I don't need to manually enter the database all the times I want to export data from it?

Alternatively, is there any way of exporting the result of a query inside my SpatiaLite database to a csv file directly? Without the need of using the commands that I used in my example?

5
  • sqlite3 should work, shouldn't it?
    – wingnut
    Commented May 7, 2021 at 2:01
  • @wingnut I guess in sqlite3 the procedure would be the same... But it's not clear to me how I can do it.
    – raylight
    Commented May 7, 2021 at 2:04
  • 1
    zetcode.com/db/sqlite/tool shows some command line options. Maybe try reading this first and having a few attempts.
    – wingnut
    Commented May 7, 2021 at 2:14
  • @wingnut Cool, it accepts the query as its second parameter after the database name. So the solution was simple: spatialite data.sqlite "select * from table" > file.csv... The only remaining issue is a way of including the header on the file without using .headers on. Although I can do it directly on the shell before writing the data to the file.
    – raylight
    Commented May 7, 2021 at 2:19
  • 1
    See answer below. Headers and CSV are command line options. zetcode.com/db/sqlite/tool shows this further down the page.
    – wingnut
    Commented May 7, 2021 at 5:23

2 Answers 2

2

In Bash, you can feed a series of lines to the stdin of a process using a "here document":

#!/bin/bash

sqlite3 test.db <<EOF
.headers on
.mode csv
select 1 as x, 2 as y, 3 as z;
EOF

which goes:

$ ./test.sh 
x,y,z
1,2,3

Everything between <<EOF and the EOF is fed to the process, as if you typed it. You can also put variables inside the document and expand them from the script.

#!/bin/bash

firstname=$1

sqlite3 test.db <<EOF
.headers on
.mode csv
select 1 as $firstname, 2 as y, 3 as z;
EOF

then you can do:

$ ./test.sh this
this,y,z
1,2,3

This is all standard Bash programming stuff, nothing special to spatialite here (I'm using sqlite3 but it will work in spatialite, I wasn't sure I had it installed). Consult a bash programming guide for more.

2
spatialite -header -csv data.sqlite "select * from table" > file.csv

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.