Over a million developers have joined DZone.

Unix File Command As An Extension To FileUtils

·
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
Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}