Ruby – Rename files in a single directory

Code:

def rando
letter=(“a”..”z”).to_a
return @name=
letter[rand(letter.length)]+”#{rand(9)}”+letter[rand(letter.length)]+
letter[rand(letter.length)]+letter[rand(letter.length)]+”#{rand(9)}”+letter[rand(letter.length)]+
letter[rand(letter.length)]+”#{rand(9)}”+letter[rand(letter.length)]+letter[rand(letter.length)]+
letter[rand(letter.length)]+letter[rand(letter.length)]+”#{rand(9)}”
end

dir = “../setup/videos”
$files = Dir.entries(dir)
puts “Before rename”
puts $files
$files.each do |f|
next if f == “.” or f == “..”
oldFile = dir + “\\” + f
newFile = dir + “\\#{rando;@name}” + “.”+f.split(“.”)[1]
File.rename(oldFile, newFile)
@file_path=File.expand_path(newFile)
@file_path=@file_path.gsub(“/”,”\\”)
end
puts “After Renamed”
$files = Dir.entries(dir)
puts $files

OUTPUT:

Before rename
.
..
four.flv
one.flv
three.flv
two.flv
After Renamed
.
..
f5vdc7zw3vplz8.flv
h5yyy5xj1jmbg8.flv
m6roa8sp5lqbq1.flv
q4rtq5ui0zdvx0.flv

Advertisements

2 thoughts on “Ruby – Rename files in a single directory

  1. mark says:

    HI, I stumbled upon your blog, while searching for something.Nice article. I have this problem with retrieving values from spreadsheet and entering it in a text field.

    The code is
    require “rubygems”
    require “watir”
    require “roo”

    module Basic
    $ie = Watir::IE.new
    def value
    oo=Openoffice.new(“D:\\test.ods”)
    oo.default_sheet = “Sheet1”
    $text = oo.cell(1,1)
    $text = $text.to_s
    end

    def searchtext

    $ie.text_field(:title, “Google Search”).set($text)

    end

    value
    searchtext

    The problem is the last letter of the string is typed twice, for ex:
    If “human” is the text i have in my spread sheet and the script feeds
    “humann” in the text field.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s