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.
This is a simple program that renames all files inside a directory.Basically, it adds underscore in the beginning of every file.
RSS feed for comments on this post · TrackBack URI
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!
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)
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)