如何在ruby中复制目录结构,不包括某些文件扩展名

时间:2009-04-02 19:44:05

标签: ruby scripting

我想编写一个ruby脚本来递归复制目录结构,但排除某些文件类型。因此,给定以下目录结构:

folder1
  folder2
    file1.txt
    file2.txt
    file3.cs
    file4.html
  folder2
  folder3
    file4.dll

我想要复制此结构,但要删除 .txt .cs 文件。 因此,生成的目录结构应如下所示:

folder1
  folder2
    file4.html
  folder2
  folder3
    file4.dll

3 个答案:

答案 0 :(得分:9)

您可以使用查找模块。这是一段代码:


require "find"

ignored_extensions = [".cs",".txt"]

Find.find(path_to_directory) do |file|
  # the name of the current file is in the variable file
  # you have to test it to see if it's a dir or a file using File.directory?
  # and you can get the extension using File.extname

  # this skips over the .cs and .txt files
  next if ignored_extensions.include?(File.extname(file))
  # insert logic to handle other type of files here
  # if the file is a directory, you have to create on your destination dir
  # and if it's a regular file, you just copy it.
end

答案 1 :(得分:2)

我不确定你的起点是什么,或者你的手动行走是什么意思,但假设你正在迭代一组文件,你可以使用reject方法根据布尔值的评估来排除项目条件。

示例:

Dir.glob( File.join('.', '**', '*')).reject {|filename| File.extname(filename)== '.cs' }.each {|filename| do_copy_operation filename destination}

在此示例中,Glob返回可枚举的文件名集合(包括目录)。您可以在拒绝过滤器中排除不需要的项目。然后,您将实现一个方法,该方法采用文件名和目标来执行复制。

你可以使用数组方法包括吗?在拒绝块中,沿着Geo的Find示例的行。

Dir.glob( File.join('.', '**', '*')).reject {|file| ['.cs','.txt'].include?(File.extname(file)) }

答案 2 :(得分:0)

也许使用一些shell脚本?

files = `find | grep -v "\.\(txt\|cs\)$"`.split
相关问题