Skip to content

Instantly share code, notes, and snippets.

/Eduardo Secret

Created October 5, 2009 03:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/065f4ed31b94bc72ffd1 to your computer and use it in GitHub Desktop.
Save anonymous/065f4ed31b94bc72ffd1 to your computer and use it in GitHub Desktop.
#!/usr/local/bin/ruby
require 'optparse'
def s2t(s)
s =~ /([0-9]{2}):([0-9]{2}):([0-9]{2}),([0-9]{3})/
t = $1.to_i * 3600000 + $2.to_i * 60000 + $3.to_i * 1000 + $4.to_i
end
def t2s(t)
h = t / 3600000; t -= h * 3600000
m = t / 60000; t -= m * 60000
s = t / 1000; t -= s * 1000
ms = t
format("%02d:%02d:%02d,%03d", h, m, s, ms)
end
optparse = OptionParser.new do |opts|
opts.banner = "Usage: shift_subtitle --operation --time "
opts.on('-o', '--operation OPERATION', [:add, :sub], "Operation") do |s|
operation = s
end
opts.on('-t', '--time TIME', "Time") do |s|
time = s
end
end
optparse.parse!
if ARGV.length == 2
input_file = ARGV[0]
output_file = ARGV[1]
else
print optparse.banner
exit(1)
end
if !(time =~ /[1-9][0-9]*|[1-9][0-9]*,[0-9]{1,3}/) then
print "invalid time\n"
exit(2)
end
ms = (time.gsub(",", ".").to_f * 1000.0).to_i
ms = -ms if operation == 'sub'
if !File.exist?(input_file) then
print "input_file #{input_file} not found\n"
exit(3)
end
f = File.new(output_file, 'w+')
File.open(input_file, 'r').each_line do |s|
s = "#{t2s(s2t($1) + ms)} --> #{t2s(s2t($2) + ms)}\n"if s =~ /([0-9]{2}:[0-9]{2}:[0-9]{2},[0-9]{3}) --> ([0-9]{2}:[0-9]{2}:[0-9]{2},[0-9]{3})/
f << s
end
f.close
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment