This week only. Pastebin PRO Accounts Christmas Special! Don't miss out!Want more features on Pastebin? Sign Up, it's FREE!
Guest

merge.rb

By: Jessehz on Aug 24th, 2011  |  syntax: Ruby  |  size: 1.31 KB  |  views: 77  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #!/usr/bin/env ruby
  2. #http://pastebin.com/KSS0zU2F
  3.  
  4. unless ARGV.count == 1
  5.         abort 'Merges sequentially-named files.'
  6. end
  7.  
  8. outfile = ARGV.first.sub(/.?\d+\z/, '')
  9.  
  10. if File.size? outfile
  11.         abort 'The outfile already exists.'
  12. end
  13.  
  14. pattern = ARGV.first.sub(/\d+\z/, '')
  15. pattern.gsub!(/[\[\]\*\{\}]/, "\\\\\\0")
  16. if digits = ARGV.first[ /\d+\z/ ]
  17.         pattern << '[0-9]' * digits.length
  18. else
  19.         pattern << '.[0-9]*'
  20. end
  21.  
  22. files = Dir.glob(pattern).sort
  23.  
  24. if files.count < 2
  25.         abort 'There needs to be at least 2 files.'
  26. end
  27.  
  28. if files.first[ /\d+\z/ ].to_i != 1
  29.         abort 'The first file in the series is missing.'
  30. end
  31.  
  32. file_count = files.last[ /\d+\z/ ].to_i
  33.  
  34. unless files.count == file_count
  35.         abort '%s of %s files are missing.' % [
  36.                 file_count-files.count, file_count
  37.         ]
  38. end
  39.  
  40. unless size = File.size?(files.first)
  41.         abort '"%s" is empty.' % files.first
  42. end
  43.  
  44. if File.size?(files.first) == File.size?(files.last)
  45.         abort 'One or more files seem to be missing.'
  46. end
  47.  
  48. files[0..-2].each do |path|
  49.         size == File.size?(path) and next
  50.         abort '"%s" has an incorrect size.' % file
  51. end
  52.  
  53. File.open outfile, 'w' do |outstream|
  54.         files.each do |path|
  55.                 puts 'Merging "%s"' % path
  56.                 File.open(path) do |instream|
  57.                         IO.copy_stream(instream, outstream)
  58.                 end
  59.         end
  60.         outstream.fsync
  61. end
  62.  
  63. files.each(&File.method(:unlink))
clone this paste RAW Paste Data