Category: Ruby & Rails

  • Ruby Rename

    You can write a “better renamer” in any scripting language, but I’m learning Ruby, so I thought i’d give it a go. I started with this basic one-liner I got from a friend

    alias rubyrename='ruby -e "a = ARGV.shift; b = ARGV.shift; ARGV.each{ |f| File.rename(f, f.gsub(a, b)) } "'

    I wanted to add some user friendliness for when i forget what the argument syntax is, so I modified it and made it into a normal script, “rubyrename.rb”

    #!/opt/local/bin/ruby
    unless ARGV.size > 2
      puts "Usage: rubyrename STRING1 STRING2 REGEXP"
      puts "       where STRING1 is to be replace with STRING2 in "
      puts "       all filenames that match REGEXP"
      exit
    end
    a = ARGV.shift
    b = ARGV.shift
    ARGV.each do |f|
      unless f == f.gsub(a, b)
        File.rename(f, f.gsub(a, b))
        puts "#{f} -> #{f.gsub(a, b)}"
      end
    end

    I also added some bells and whistles

    Example:

    artemis:~/temp daniel$ ls
    foofoofoo.01    foofoofoo.02    foofoofoo.03
    artemis:~/temp daniel$ rubyrename.rb foo bar *
    foofoofoo.01 -> barbarbar.01
    foofoofoo.02 -> barbarbar.02
    foofoofoo.03 -> barbarbar.03
    
    artemis:~/temp daniel$ rubyrename.rb bar foobar *
    barbarbar.01 -> foobarfoobarfoobar.01
    barbarbar.02 -> foobarfoobarfoobar.02
    barbarbar.03 -> foobarfoobarfoobar.03
    
    artemis:~/temp daniel$ ls
    foobarfoobarfoobar.01   foobarfoobarfoobar.02   foobarfoobarfoobar.03

    Now all I have to do is alias a shorter command to my rubyrename script in my .profile

    alias rrn=rubyrename.rb
    

    Of course rubyrename.rb needs to be in my path, or I could have specified the full path in the alias