How to rename a file in Ruby?

时光总嘲笑我的痴心妄想 提交于 2019-11-28 17:23:45

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)

Nicola Mingotti

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!