重命名相同路径中的文件(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.cssI 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 endmy 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更多推荐
发布评论