使用Ruby重命名所有子目录

时间:2013-09-04 10:56:20

标签: ruby

我在Windows 7计算机上有一个深层嵌套的文件夹结构。 Windows拒绝删除目录,因为它们的名称太长。我想将所有子文件夹重命名为2,希望它足够短以便删除。这是我的剧本:

@count = 0

Dir.glob("**/*") do |file|  #find src files in current folder and all subfolders
  if File.directory?(file)
    File.rename(file, File.dirname(file) + File::SEPARATOR + "2")
    @count += 1
  end
end

puts @count

当脚本运行时,它不是重命名所有子目录,而是更改一个子目录,每次逐渐深入一级。即,目前运行脚本的输出是:

C:\>renamer.rb
30
C:\>renamer.rb
31
C:\>renamer.rb
32

我很困惑为什么会这样,并且会感激任何意见。

我采取了正确的方法吗?我假设Ruby的递归目录删除方法会失败。但是,当我尝试执行

require "FileUtils"
FileUtils.remove_dir ("2", force = true)

我收到错误

syntax error, unexpected ',', expecting ')'
FileUtils.remove_dir ("2", force = true)
                          ^
syntax error, unexpected ')', expecting end-of-input
FileUtils.remove_dir ("2", force = true)
                                    ^

1 个答案:

答案 0 :(得分:1)

问题是Dir.glob("**/*")返回如下数组:

['folder', 'folder/sub', 'folder/sub/sub']

现在你做的时候:

File.rename(file, File.dirname(file) + File::SEPARATOR + "2")

它将重命名folder,但当它到达folder/sub时,它已不再存在,因为您已将folder重命名为2:它将是2/sub代替folder/sub。解决方案是反转阵列。这将在最深层次上开始重命名过程,并逐步达到顶层:

Dir.glob("**/*").reverse.each do |file|
  # rest of your code can stay the same
end

至于你的第二个问题,而不是:

FileUtils.remove_dir ("2", force = true)

您应该使用:

FileUtils.remove_dir("2", true)

首先,确保remove_dir(之间没有空格。导致错误的是什么。

此外,force是参数的名称,默认情况下为false。这就是您看到force = false in the API的原因。如果您希望forcetrue可以true简单地传递给该函数,就像我在上面所示。

相关问题