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"

$ 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.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"'

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

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.


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

No comments:

Post a Comment