Thursday, May 1, 2014

Ruby Scripts for File Management Tasks

Lately, I have been using Ruby more frequently for file management activities.

I used to create Bash Scripts for nearly every thing.

Now, I'll typically open an IRB console, hammer out a few lines of Ruby code and be done.

Next, slap that work into a Ruby Script file and have it available for next time.

Commands to Change File Extensions


$ find . -name "*.erb"
./jquery.ui.accordion.css.erb
./jquery.ui.all.css.erb
./jquery.ui.autocomplete.css.erb
./jquery.ui.base.css.erb
./jquery.ui.button.css.erb
./jquery.ui.core.css.erb
./jquery.ui.datepicker.css.erb
./jquery.ui.dialog.css.erb
./jquery.ui.menu.css.erb
./jquery.ui.progressbar.css.erb
./jquery.ui.resizable.css.erb
./jquery.ui.selectable.css.erb
./jquery.ui.slider.css.erb
./jquery.ui.spinner.css.erb
./jquery.ui.tabs.css.erb
./jquery.ui.theme.css.erb
./jquery.ui.tooltip.css.erb

$ irb
>> Dir.glob("*.erb").each{|i| `mv #{i} #{i.slice(0..-5)}`};nil
>> Dir.glob("*.*")
=> ["jquery.ui.accordion.css", "jquery.ui.all.css", "jquery.ui.autocomplete.css", "jquery.ui.base.css", "jquery.ui.button.css", "jquery.ui.core.css", "jquery.ui.datepicker.css", "jquery.ui.dialog.css", "jquery.ui.menu.css", "jquery.ui.progressbar.css", "jquery.ui.resizable.css", "jquery.ui.selectable.css", "jquery.ui.slider.css", "jquery.ui.spinner.css", "jquery.ui.tabs.css", "jquery.ui.theme.css", "jquery.ui.tooltip.css"]


Create Ruby Script

With a little more effort, we can create a useful ruby script from that logic.

#!/usr/bin/env ruby

# filename:  change-file-ext
# author:    Lex Sheehan
# copyright: Lex Sheehan LLC
# license:   GPL
# status:    production
# comments:  changes file extensions in current directory

def usage
  puts 'Usage:   change-file-ext  '
  puts 'Example: change-file-ext "css.erb" "css"'
  exit
end

if ARGV.size < 2 || ARGV.include?('--h')
  usage
else
  from_ext = "*.#{ARGV[0]}"
  to_ext = ARGV[1]
end

Dir.glob(from_ext).each{|i| `mv #{i} #{i.slice(0..-from_ext.size)}.#{to_ext}` }



File Header Comments

The file header comments do not include version information, as that information should be stored in the source file repository, e.g. github.

Notes

Don't forget to make the script executable: chmod +x change-file-ext

No comments:

Post a Comment