delete
delete

Reputation:

How to rename a file in Ruby?

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?

Upvotes: 68

Views: 70622

Answers (5)

Nicola Mingotti
Nicola Mingotti

Reputation: 998

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.

Upvotes: 0

boulder_ruby
boulder_ruby

Reputation: 39695

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`

Upvotes: 23

Steve
Steve

Reputation: 21499

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

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

Upvotes: 1

Preacher
Preacher

Reputation: 2420

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.

Upvotes: 29

Mat
Mat

Reputation: 206699

What about simply:

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

Upvotes: 108

Related Questions