How to copy directory structure in ruby, except for certain file extensions

I want to write a ruby ​​script to recursively copy the directory structure, but exclude some file types. So, given the following directory structure:

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

I want to copy this structure, but exlcude .txt and .cs files. So, the resulting directory structure should look like this:

folder1
  folder2
    file4.html
  folder2
  folder3
    file4.dll
+5
source share
3 answers

You can use the find module . Here's the code snippet:


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 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 a regular file, you just copy it.
end
+9
source

, , , reject .

:

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

Glob ( ). , . , , .

? Geo.

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

Perhaps some shell scripts are used?

files = `find | grep -v "\.\(txt\|cs\)$"`.split
0
source

All Articles