Skip to content

Instantly share code, notes, and snippets.

@carter-yagemann
Created January 13, 2017 17:51
Show Gist options
  • Save carter-yagemann/ee61d5b32553f2d8b1c2a587051e1f45 to your computer and use it in GitHub Desktop.
Save carter-yagemann/ee61d5b32553f2d8b1c2a587051e1f45 to your computer and use it in GitHub Desktop.
epubgrep
"""
Simplifies the process of grepping EPUB files.
Grep must be installed for this script to work.
Copyright (c) 2016 Carter Yagemann
Permission is hereby granted, free of charge, to any person obtaining a copy of this
software and associated documentation files (the "Software"), to deal in the Software
without restriction, including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""
import shutil
import subprocess
import sys
import tempfile
import zipfile
if len(sys.argv) < 3:
print "Usage: epubgrep <expression> <epub>"
sys.exit()
regex = sys.argv[1]
epub = sys.argv[2]
temp = tempfile.mkdtemp()
# Extract EPUB into a temp directory
with zipfile.ZipFile(epub, "r") as file:
file.extractall(temp)
# Grep temp directory
args = ['grep', '-R', '-h', '--color=never', regex, temp]
process = subprocess.Popen(args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = process.communicate()
print out
# Delete temp directory
shutil.rmtree(temp)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment