重命名相同路径中的文件(Rename files in same path)

编程入门 行业动态 更新时间:2024-10-27 10:22:54
重命名相同路径中的文件(Rename files in same path)

我正在尝试编写一个方法,将所有.new文件扩展名重命名为一个新名称,我已经看过类似的帖子,但没有像我要求的那样具体。

我的代码需要重命名它所在目录中的文件。因为该方法正在搜索多个目录。 我写的代码重命名根目录中的文件。

此函数将在多个目录上运行,因此使用pathname = "/path/to/app/"对我来说不起作用。 这是代码:

dotNewFiles = File.join("**", "*.new") Dir.glob(dotNewFiles).each do |f| filename = File.basename(f, File.extname(f)) #keep it commented until it works #File.rename(f, filename) print "Renamed File from:\t" printf "%-50s %s\n", f, "to".upcase + "\t" + filename end

我的输出看起来像这样:

Renamed File from: app/assets/javascripts/application.js.new TO application.js Renamed File from: app/assets/stylesheets/application.css.new TO application.css

I am trying to write a method that will rename all .new file extensions to a new name I have seen similar post but nothing as specific as what i am asking.

my code needs to rename the files in the directory it is in. since the method is searching multiple directories. the code I have written renames the files in the root directory.

this function will be ran on multiple directories so using pathname = "/path/to/app/" will not work for me. here is the code:

dotNewFiles = File.join("**", "*.new") Dir.glob(dotNewFiles).each do |f| filename = File.basename(f, File.extname(f)) #keep it commented until it works #File.rename(f, filename) print "Renamed File from:\t" printf "%-50s %s\n", f, "to".upcase + "\t" + filename end

my output looks like this:

Renamed File from: app/assets/javascripts/application.js.new TO application.js Renamed File from: app/assets/stylesheets/application.css.new TO application.css

最满意答案

Dir.glob('**/*.new').each do |f| filename = File.expand_path('../' + File.basename(f, File.extname(f)), f) # or # filename = f.sub(/\.new$/, '') File.rename(f, filename) print "Renamed File from:\t" printf "%-50s %s\n", f, "to".upcase + "\t" + filename end Dir.glob('**/*.new').each do |f| filename = File.expand_path('../' + File.basename(f, File.extname(f)), f) # or # filename = f.sub(/\.new$/, '') File.rename(f, filename) print "Renamed File from:\t" printf "%-50s %s\n", f, "to".upcase + "\t" + filename end

更多推荐

本文发布于:2023-08-07 20:14:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465646.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路径   重命名   文件   path   files

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!