Skip to content

Instantly share code, notes, and snippets.

@ip413
Last active November 3, 2019 20:43
Show Gist options
  • Save ip413/b9ba9b22a41539b4d94fa27729e1a3cc to your computer and use it in GitHub Desktop.
Save ip413/b9ba9b22a41539b4d94fa27729e1a3cc to your computer and use it in GitHub Desktop.
#!/usr/bin/ruby
if ARGV.length == 0
puts <<HELP
Script extracts Kindle Clippings for specified book into external file, with formatting:
=== location 340
Clipping content xyz
=== page 450
Clipping content abc
Usage:
./read_kindle_clipings.rb [clippings_file_location]
HELP
exit 0
end
@clippings = Array.new
@books = Array.new
@clippings_for_book = Array.new
def get_clippings(file_content)
file_content.split(/={10}\r?\n?/).each { |clipping| @clippings << clipping if !clipping.strip.empty?}
end
def get_books
@clippings.each do |clipping|
title_search = clipping.gsub(/(.*?)(\r?\n.*)/, '\1')
@books << title_search.strip if !title_search.empty?
end
@books.uniq!
@books.each_with_index {|book, i| print i, " ", book, "\n"}
end
def get_clippings_for_book(book_index)
title = @books[book_index]
p title
@clippings.each do |clipping|
@clippings_for_book << clipping if clipping.start_with?("#{title}")
end
end
def format_clippings_for_book
@clippings_for_book.each do |clipping|
location = clipping.scan(/((?:location|page).*\|)/).first[0].strip
# removing everthing before content and adding line with location
clipping.gsub!(/.*?\r?\n.*?\r?\n\r?\n/, "=== " + location + "\n")
end
end
filename = ARGV[0]
get_clippings(File.read(filename))
get_books
print "\n\nEnter book index to extract clippings: "
book_index = $stdin.gets.chomp.to_i
get_clippings_for_book book_index
format_clippings_for_book
out_file_name = @books[book_index].gsub(/[^a-zA-Z ]+/, '') + ".txt";
File.write(out_file_name, "# #{@books[book_index]} \n\n\n#{@clippings_for_book.join("\n\n")}")
puts "\n", "File was written to:\n#{out_file_name}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment