Skip to content

Instantly share code, notes, and snippets.

@dtan4
Created April 17, 2013 18:57
Show Gist options
  • Save dtan4/5406796 to your computer and use it in GitHub Desktop.
Save dtan4/5406796 to your computer and use it in GitHub Desktop.
Divide GPX file into segments
#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
require 'nokogiri'
def divide(filename)
gpx = Nokogiri::XML(File.read(filename))
segment_count = gpx.xpath('//xmlns:trkseg').length
segment_count.times do |i|
# aaa.gpx -> aaa-0.gpx
seg_filename = filename.gsub(/(.*)\.([0-9a-zA-Z]+)/, "\\1-#{i + 1}.\\2")
seg_gpx = gpx.dup
seg_trksegs = seg_gpx.xpath('//xmlns:trkseg')
seg_trksegs.each_with_index { |seg_trkseg, j| seg_trkseg.remove if j != i }
File.open(seg_filename, "w") { |file| file.puts seg_gpx.to_s }
end
end
if ARGV.length < 1
STDERR.puts "error: no argument"
exit 1
end
filename = ARGV[0]
divide(filename)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment