Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename a file in Ruby?

Tags:

file

ruby

dir

People also ask

What is the method of rename () a file?

To rename a file or folder:Right-click on the item and select Rename, or select the file and press F2 . Type the new name and press Enter or click Rename.


What about simply:

File.rename(f, folder_path + "/" + filename.capitalize + File.extname(f))

Doesn't the folder_path have to be part of the filename?

puts "Renaming files..."

folder_path = "/home/papuccino1/Desktop/Test/"
Dir.glob(folder_path + "*").sort.each do |f|
  filename = File.basename(f, File.extname(f))
  File.rename(f, folder_path + filename.capitalize + File.extname(f))
end

puts "Renaming complete."

edit: it appears Mat is giving the same answer as I, only in a slightly different way.


If you're running in the same location as the file you want to change

File.rename("test.txt", "hope.txt")

Though honestly, I sometimes I don't see the point in using ruby at all...no need probably so long as your filenames are simply interpreted in the shell:

`mv test.txt hope.txt`

If you are on a linux file system you could try mv #{filename} newname

You can also use File.rename(old,new)