How to rename a file in Ruby?

RubyFileDir

Ruby Problem Overview


Here's my .rb file:

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, filename.capitalize + File.extname(f))
end

puts "Renaming complete."

The files are moved from their initial directory to where the .rb file is located. I'd like to rename the files on the spot, without moving them.

Any suggestions on what to do?

Ruby Solutions


Solution 1 - Ruby

What about simply:

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

Solution 2 - Ruby

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.

Solution 3 - Ruby

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`

Solution 4 - Ruby

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

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

Solution 5 - Ruby

Don't use this pattern unless you are ready to put proper quoting around filenames:

`mv test.txt hope.txt`

Indeed, suppose instead of "hope.txt" you have a file called "foo the bar.txt", the result will not be what you expect.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondeleteView Question on Stackoverflow
Solution 1 - RubyMatView Answer on Stackoverflow
Solution 2 - RubyPreacherView Answer on Stackoverflow
Solution 3 - Rubyboulder_rubyView Answer on Stackoverflow
Solution 4 - RubySteveView Answer on Stackoverflow
Solution 5 - RubyNicola MingottiView Answer on Stackoverflow