0

我正在尝试编写一种将所有 .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
4

2 回答 2

0

您必须考虑目录,例如:

Dir.glob(dotNewFiles).each do |f|
  dirname, basename = File.split(f)           # split filename into directory and basename
  basename = File.basename(basename, ".new")  # change basename
  filename = File.join(dirname, basename)     # join directory and new basename
  File.rename(f, filename)
end
于 2013-05-08T16:48:04.087 回答
0
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
于 2013-05-08T15:46:35.177 回答