Skip to content

Instantly share code, notes, and snippets.

@iluvcapra
Created January 31, 2009 09:25
Show Gist options
  • Save iluvcapra/55494 to your computer and use it in GitHub Desktop.
Save iluvcapra/55494 to your computer and use it in GitHub Desktop.
Sort a folder of files into folders
#!/usr/bin/env ruby
#
# Created by Jamie Hardt on 2007-01-13.
# Copyright (c) 2007. All rights reserved.
require 'find'
files = { }
raise ArgumentError unless (filesPath = ARGV[0] and destPath = ARGV[1])
Find.find(filesPath) do |path|
if File.file?(path) then
daykey = File.ctime(path).strftime("%Y-%m-%d")
files[daykey] = [] if files[daykey] == nil
files[daykey] << path if ( File.file?(path) && File.basename(path)[0] != ?. )
end
end
Dir.chdir(destPath)
files.each do |folder,paths|
Dir.mkdir(folder)
paths.each do |path|
dest_name = folder + File::SEPARATOR
dest_name << ( base = File.basename(path) )
i = 1
while(File.exist?(dest_name)) do
dest_name = folder + File::SEPARATOR
md = base.match(/(.*)(\.[a-zA-Z0-9]*)/)
dest_name << if md then
md[1] + (".%02i" % [ i ]) + md[2]
else
base + (".%02i" % [ i ])
end
i += 1
end
File.rename(path,dest_name)
$stderr.print "moving\n %s\n to %s\n\n" % [path , dest_name]
end
Dir.chdir(destPath)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment