Skip to content

Instantly share code, notes, and snippets.

@akm
Last active November 29, 2016 23:25
Show Gist options
  • Select an option

  • Save akm/7ec70c7061d8d8dd129b8a6461bef946 to your computer and use it in GitHub Desktop.

Select an option

Save akm/7ec70c7061d8d8dd129b8a6461bef946 to your computer and use it in GitHub Desktop.
vcard to csv
#!/usr/bin/env ruby
# coding: utf-8
#
# ## Setup
# gem install vpim activesupport
#
# ## Usage
# ENCODING=SJIS vcard_to_csv.rb input.vcf > path/to/output.csv
#
# input.vcf は連絡先アプリ(Address Book)のグループなどから出力したファイル
require 'csv'
require 'vpim/vcard'
require 'active_support/multibyte/unicode'
headers = %w[familyname, givenname, spouse, postalcode, fulladdress]
encoding = ENV['ENCODING'] || 'UTF-8'
PATTERNS = {
/−/ => '‐'
}
data = Vpim::Vcard.decode(ARGF).map do |vcard|
next unless addr = vcard.address
full_addr = [addr.region, addr.locality, addr.street].map{|s| s.strip }.join(" ")
line = vcard.lines("X-ABRELATEDNAMES").first
spouse = line ? line.value : ''
[vcard.name.family, vcard.name.given, spouse, addr.postalcode, full_addr].map do |s|
# t = ActiveSupport::Multibyte::Unicode.normalize(s, :kc)
t = s
PATTERNS.each do |ptn, rep|
t.gsub!(ptn, rep)
end
begin
t.encode(encoding)
rescue Exception => e
$stderr.puts "-" * 100
$stderr.puts s
raise
end
end
end.compact
r = CSV.generate("", write_headers: true, headers: headers) do |csv|
data.each { |d| csv << d }
end
puts r
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment