We've organized files in subdirectories according to tags and according to creation date. What if you would like to flatten a tree, moving all files from the sub-directories into a single directory?
"Move all the files from the tree starting at source_dir"
"into dest_dir out of the tree"
def flatten(source_dir, dest_dir)
Dir.foreach(source_dir) do |filename|
# exclude current dir and parent dir
if (!filename.eql?(".") and !filename.eql?(".."))
if File.directory?(filename) # subdirectory
flatten(filename, dest_dir) # recursively flatten subdir
else #file
dirname = File.dirname(filename)
filenameonly = filename[(dirname.length-1)..-1]
old_name = source_dir + "/" + filename
new_name = dest_dir + "/" + filenameonly
puts("moving '#{old_name}' to '#{new_name}'")
File.rename(old_name, new_name)
end
end
end
end
# read line parameters
source_dir = ARGV.shift
# default source dir is current dir
if (source_dir == nil)
source_dir = "."
end
dest_dir = ARGV.shift
# default destination dir current dir
if (dest_dir == nil)
dest_dir = "."
end
flatten(source_dir, dest_dir)
0 commenti:
Posta un commento