Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A quick script to convert the XML from Android app "SMS Backup & Restore" into CSV.
#!/usr/bin/env ruby
# A quick script to convert the XML from Android app "SMS Backup & Restore" into CSV.
#
# Usage: $ ./sms-backup-to-csv.rb < PATH/TO/BACKUP/FILE.xml
require "nokogiri"
require "csv"
# Specify the backup file's attributes and data types.
COLUMNS = { "protocol" => :to_i, "address" => :to_s, "date" => :to_i, "type" => :to_i, "subject" => :to_s, "body" => :to_s, "toa" => :to_i, "sc_toa" => :to_i, "service_center" => :to_s, "read" => :to_i, "status" => :to_i, "locked" => :to_i, "date_sent" => :to_s, "readable_date" => :to_s, "contact_name" => :to_s }
# Read backup file from stdin and into Nokogiri.
backup = Nokogiri::XML ARGF.read
# Pluck out just the SMS nodes
messages = backup.css("sms")
# For each message, grab and convert each attribute specified above.
rows = messages.map { |m| COLUMNS.map {|k,v| m.attribute(k).content.method(v).call }}
# Write the data as a CSV to stdout.
CSV do |stdout|
stdout << COLUMNS.keys
rows.each {|r| stdout << r }
end
@twehman

This comment has been minimized.

Copy link

@twehman twehman commented Oct 19, 2019

No real experience with Ruby - how would I alter this to write to a file instead of stdout?

@jsvine

This comment has been minimized.

Copy link
Owner Author

@jsvine jsvine commented Oct 22, 2019

With any command line script in Unix, you can redirect stdout to a file, using the > operator. E.g., for this script:

./sms-backup-to-csv.rb < PATH/TO/BACKUP/FILE.xml > my-new-file.csv
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.