2009-04-02 3 views
5

Chcę napisać skrypt ruby, aby rekurencyjnie skopiować strukturę katalogów, ale wykluczyć niektóre typy plików. Tak więc, biorąc pod uwagę następującą strukturę katalogów:Jak skopiować strukturę katalogów w ruby, z wyjątkiem niektórych rozszerzeń plików

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

Chcę skopiować tę strukturę, ale exlcude .txt i .cs plików. Tak powstała struktura katalogu powinna wyglądać następująco:

folder1 
    folder2 
    file4.html 
    folder2 
    folder3 
    file4.dll 

Odpowiedz

1

Nie jestem pewien, co jest punktem wyjścia, albo co masz na myśli poprzez ręczne chodzenia, ale przy założeniu, że iteracja nad kolekcją plików możesz użyć metody odrzucania, aby wykluczyć elementy na podstawie oceny warunku boolowskiego.

przykład:

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

W tym przykładzie, Glob zwraca enumerable zbiór nazw plików (w tym katalogów). Wykluczasz elementy, których nie chcesz w filtrze odrzuceń. Następnie zaimplementujesz metodę, która pobiera nazwę pliku i miejsce docelowe, aby wykonać kopię.

Można użyć metody tablicowej? w bloku odrzuć również wzdłuż przykładu Find z Geo.

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

można użyć znaleźć moduł. Oto fragment kodu:


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 
0

Może użyć skryptów powłoki?

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