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

Mik*_*ond 5 ruby scripting

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

folder1
  folder2
    file1.txt
    file2.txt
    file3.cs
    file4.html
  folder2
  folder3
    file4.dll
Run Code Online (Sandbox Code Playgroud)

我想复制这个结构,但是exlcude .txt.cs文件.因此,生成的目录结构应如下所示:

folder1
  folder2
    file4.html
  folder2
  folder3
    file4.dll
Run Code Online (Sandbox Code Playgroud)

Geo*_*Geo 9

您可以使用find模块.这是一段代码片段:


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
Run Code Online (Sandbox Code Playgroud)


Jas*_*rue 2

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

例子:

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

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

可以使用数组方法include吗?也在拒绝块中,沿着 Geo 的 Find 示例的思路。

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