DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Unix File Command As An Extension To FileUtils

07.20.2009
| 4275 views |
  • submit to reddit
        I recently needed to make sure all my files were named according to their content rather than to an arbitrary extension that had been added to them. This resulted in extending the ruby FileUtils to use the Unix file command to return the filename and type as array elements so with a script argument of:

/var/testfiles/*

you get an output of:

[["/var/testfiles/movie_quiz_for_wiggy.doc", "Microsoft Office Document"], ["/var/testfiles/movie_quiz_for_wiggy.odt", "OpenDocument Text"], ["/var/testfiles/movie_quiz_for_wiggy.pdf", "PDF document, version 1.4"]]

#!/usr/bin/env ruby
require 'fileutils'

module FileUtils
  unless RUBY_PLATFORM=~/win[36]/
    def self.file(src)
      `file #{src}`.split("\n").collect {|x| x.split(":",2).collect {|y| y.strip}}
    end
  end
end

p(FileUtils.file(ARGV[0]))

Enjoy!
Paul McKibbin
http://www.pqmf.com