重命名相同路径中的文件

时间:2013-05-08 15:36:11

标签: ruby-on-rails ruby

我正在尝试编写一个方法,将所有.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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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