复制文件时制作子目录

时间:2015-02-07 09:16:04

标签: ruby

我有简单的脚本,它通过txt文件并根据txt文件中的行复制文件

这是

require 'fileutils'


File.open("files.txt", "r") do |f|
  f.each_line do |line|
    line = line.chop  #need to remove \n symbol from like
    system("cp #{line} new/#{line}")
  end
end

在我的txt文件中 - 每个文件路径都像:

app/helpers/api/v1/application_helper.rb

然而,当我运行脚本时,如果我的new文件夹中没有这样的目录,它将失败。因此,我必须手动创建它们以反映文件夹结构,如在我的txt文件中,或者使用脚本创建。

有什么办法可以在我的剧本中做到这一点吗?

2 个答案:

答案 0 :(得分:2)

有很多方法可以解决这个问题。这是一种方法:

require 'fileutils'

File.open("files.txt", "r") do |f|
  f.each_line do |line|
    line = line.chop
    system("mkdir -p new/#{File.dirname(line)}")
    system("cp #{line} new/#{line}")
  end
end

答案 1 :(得分:1)

我发现你需要fileutils但不要使用任何方法。你可以像这样使用它

require 'fileutils'

File.open("files.txt", "r") do |f|
  f.each_line do |line|
    line = line.chop  #need to remove \n symbol from like

    FileUtils.mkdir_p(File.dirname(line))
    FileUtils.cp(line, "new/#{line}")
  end
end