# charset="CP932" # encoding="CP932" # File を整理整頓してるつもり。 # Sub directory は調べません。 # Perl と Python とで若干内容が違いますが。 # Platform に依存しない筈です。多分 #!/usr/bin/env perl require 5.002; use File::Path; use Getopt::Std; use strict; use vars qw{ $opt_e $opt_n $opt_r $opt_y }; getopts('enr:y'), ($opt_e || $opt_n || $opt_r || $opt_y) or die <<"."; Usage: ${\(split '/', $0)[-1]} -[e,n,r'REGEXP',y] e: by extension. n: by word 1st and 2nd of file name. r: by regexp. y: by year. . $_{sep} = $^O =~ /MacOS/ ? ':' : $^O =~ /DOS|Win32|OS2/i ? '\\' : '/'; while (defined($_{dir} = shift @ARGV)) { -d $_{dir} or next; opendir _, $_{dir} or die; for (sort grep !/^\./, readdir _) { $_{arg} = join $_{sep}, $_{dir}, $_; -f $_{arg} or next; if ($opt_e) { my @e = split /\./; next unless @e > 1 and $e[-1]; $e[-1] =~ s/s?html?$/html/i; $e[-1] =~ s/jpeg$/jpg/i; $_{path} = join $_{sep}, $_{dir}, $e[-1]; } elsif ($opt_n) { my @d = /^([a-zA-Z]+)[^a-zA-Z0-9]+([a-zA-Z]+)/; next unless $d[0] and $d[1]; $_{path} = join $_{sep}, $_{dir}, @d; } elsif ($opt_r) { /$opt_r/o or next; $_{path} = join $_{sep}, $_{dir}, ($1 || $&); } elsif ($opt_y) { my $y = (stat $_{arg})[9]; next unless $y; $_{path} = join $_{sep}, $_{dir}, 1900 + (localtime $y)[5]; } $_{path} or next; -d $_{path} or mkpath([$_{path}], 1, 0755) or die "1:$_{path}\n$!"; $_{file} = join $_{sep}, $_{path}, $_; rename $_{arg}, $_{file} or die "0:$_{arg}\n2:$_{file}\n$!"; # warn "--> $_{file}\n"; } closedir _; } __END__ #!/usr/bin/env python import getopt import os import re import string import sys def makedirs(n): if not os.path.exists(n): os.makedirs(n) return n def eachfile(d, b): global dt, ot if b[0] == '.': return m = dt.search(b) if m == None: return if ot == '-f': n = os.path.join(makedirs(os.path.join(d, m.group(1))), m.group(2)) else: n = os.path.join(d, m.group(1)) os.rename(os.path.join(d, b), os.path.join(makedirs(n), b)) def ls(d): for b in os.listdir(d): if os.path.isfile(os.path.join(d, b)): eachfile(d, b) def name_type(t='-n'): return re.compile({ '-e': r'\.([a-zA-Z0-9]+)$', '-f': r'^([a-zA-Z]+)[^a-zA-Z0-9.]+([a-zA-Z]+)', '-n': r'^([0-9]+|[a-zA-Z]+|[^a-zA-Z0-9]+)', }[t]) def usage(): print "Usage:", sys.argv[0], """-[efn] e: by Extension. f: by 1st and 2nd word of file name. n: by 1st word of file name. """ sys.exit() def optget(): global dt, ot opts, args = getopt.getopt(sys.argv[1:], 'efny') if not opts: usage() ot = opts[0][0] dt = name_type(ot) if not dt: usage() return args if __name__ == '__main__': args = optget() for i in args: if os.path.isdir(i): ls(i) elif os.path.isfile(i): d, b = os.path.split(i) eachfile(d, b)