Skip to content

Instantly share code, notes, and snippets.

@shaoshing
Last active August 2, 2022 20:43
Show Gist options
  • Save shaoshing/4982492 to your computer and use it in GitHub Desktop.
Save shaoshing/4982492 to your computer and use it in GitHub Desktop.
Ruby script to convert Numbers file to txt, so that it can be imported into Supermemo.
#!/usr/bin/env ruby
#
# Usages
# num2txt path/to/your/file.numbers
require 'csv'
if !ARGV[0]
puts "Please specify a number file."
exit
end
number = File.expand_path(ARGV[0])
csv = number.sub(".numbers", ".csv")
txt = number.sub(".numbers", ".txt")
puts "== getting Numbers to export to csv"
`
osascript -e '
on run argv
set number_file to item 1 of argv
set csv_path to (text 1 thru -8 of number_file) & "csv" -- replace name extension
tell application "Numbers"
open number_file
save document 1 as "LSDocumentTypeCSV" in csv_path
close every window saving no
end tell
end run
' "#{number}"
`
file = File.read(csv)
File.delete(csv)
file.gsub!("\C-M", "\n").gsub!(/\n{2,}/, "\n")
puts "== converting to QA"
content = CSV.parse(file).map do |cells|
next unless cells[0]
entry = ""
cells[0].each_line do |line|
entry += "Q: " + line + "\n"
end
cells[1].each_line do |line|
entry += "A: " + line + "\n"
end
entry.gsub(/(\n|\r|\r\n){2,}/,"\n")
end.join("\n")
puts "== checking formats"
invalid = false
content.each_line do |line|
if line !~ /^(Q|A|\n)/
puts " malformed line: #{line}"
invalid = true
end
end
if invalid
puts " (faild to convert this file!)"
exit
end
File.write(txt, content)
puts "== Done!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment