Skip to content

Instantly share code, notes, and snippets.

@shaunkane
Created January 9, 2017 17:38
Show Gist options
  • Save shaunkane/6b21e48e5bbd54f76806f0a13f19e79a to your computer and use it in GitHub Desktop.
Save shaunkane/6b21e48e5bbd54f76806f0a13f19e79a to your computer and use it in GitHub Desktop.
Script for automating Bear note backups. Note that you must fill in the BEAR_DB and EXPORT_DIR variables for this to work.
# export notes from the Bear db to markdown files
import sqlite3
BEAR_DB = '/Users/<your username>/Library/Containers/net.shinyfrog.bear/Data/Library/Application Support/net.shinyfrog.bear/database.sqlite'
EXPORT_DIR = '<set an export directory>'
conn = sqlite3.connect(BEAR_DB)
c = conn.cursor()
for row in c.execute('SELECT ZTITLE, ZTEXT FROM ZSFNOTE'):
# strips unicode characters in the note title/file name (which prevents errors backing up to Dropbox)
title = row[0].encode('ascii','ignore').strip()
text = row[1].encode('UTF-8')
fname = EXPORT_DIR + title + '.md'
with open(fname,'w') as outfile:
outfile.write(text)
conn.close()
@glxxyz
Copy link

glxxyz commented Oct 27, 2018

Thanks for this- it's been useful. I noticed one flaw though- if two notes have the same title, one overwrites the other, so I fixed that by adding part of the note's UID to the filename. Also I wanted to avoid overwriting files that haven't changed, so I check the existing outputted file's contents. These are fixed in this version:

import sqlite3, urllib, os.path

BEAR_DB = '/Users/<path to your Bear db>/database.sqlite'
EXPORT_DIR = '<set an export directory>'

with sqlite3.connect(BEAR_DB) as conn:
    c = conn.cursor()
    for row in c.execute('SELECT ZTITLE, ZTEXT, ZUNIQUEIDENTIFIER FROM ZSFNOTE'):
        # strip unicode characters, quote for clean filename, limit to avoid length issues
        title = row[0].encode('ascii', 'backslashreplace').strip()
        title = urllib.quote(title, " ")
        title = title[:100]
        text = row[1].encode('UTF-8')
        # part of the uid should be unique enough
        uid = row[2].encode('ascii').split("-")[0]
        fname = EXPORT_DIR + title + "." + uid + '.md.txt'
        if os.path.isfile(fname):
            with open(fname, 'r') as infile:
                if infile.read() == text:
                    continue
        with open(fname, 'w') as outfile:
            outfile.write(text)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment