Renaming files using ruby!

This is a simple program that renames all files inside a directory.Basically, it adds underscore in the beginning of every file.


These icons link to social bookmarking sites where readers can share and discover new web pages.

  • Digg
  • del.icio.us
  • Netvouz
  • DZone
  • ThisNext
  • MisterWong
  • Wists
  • blinkbits
  • BlinkList

3 Comments »

  1. Derek said,

    August 14, 2007 @ 9:58 pm

    What happens if a file already exists with the new name?
    i.e. you call”

    File.rename(’myfile.txt’, ‘_myfile.txt’)

    when ‘_myfile.txt’ exists.

    Sorting may prevent this, assuming nothing sorts before the “_” character

    Nice site, very pretty!

  2. Pink Chocobo said,

    March 17, 2008 @ 11:42 am

    Here is a variation - it will ask what you want as a prefix (in my case, renaming music files)

    #/Users/kriplean/desktop/ruby/renamev2.rb

    def rename_files_in_directory(dir, add_this_text)
    files = Dir.entries(dir)
    files.each do |filename|
    next if filename == “.” or filename == “..”
    oldFile = dir + “/” + filename
    newFile = dir + “/” + add_this_text + filename
    puts add_this_text + filename
    File.rename(oldFile, newFile)
    end
    end

    dir = “/Users/myusername/desktop/files”
    puts “Type the Artist Name:”
    add_this_text = gets.chomp
    rename_files_in_directory(dir, add_this_text)

  3. Pink Chocobo said,

    March 17, 2008 @ 11:42 am

    Here is a variation - it will ask what you want as a prefix (in my case, renaming music files)

    #/Users/kriplean/desktop/ruby/renamev2.rb

    def rename_files_in_directory(dir, add_this_text)
    files = Dir.entries(dir)
    files.each do |filename|
    next if filename == “.” or filename == “..”
    oldFile = dir + “/” + filename
    newFile = dir + “/” + add_this_text + filename
    puts add_this_text + filename
    File.rename(oldFile, newFile)
    end
    end

    dir = “/Users/myusername/desktop/files”
    puts “Type the Artist Name:”
    add_this_text = gets.chomp
    rename_files_in_directory(dir, add_this_text)

RSS feed for comments on this post · TrackBack URI

Leave a Comment