Often encounter downloaded files or e-books, the name contains a number of web site information, the actual use because the name is too long inconvenient, the following script uses regular expressions to rename all the files under the directory:
For example:
Prior to modification: [cloud-Habitat community]mac OS X for Unix Geeks[www.jb51.net].mobi
Modified: Mac OS X for Unix Geeks.mobi
The Python code is as follows:
Copy Code code as follows:
Import OS
Import re
Def rename_dir (dir,regex,f):
If not os.path.isdir (dir) or not os.path.exists (dir):
Print ("The" the input is not one directory or not exist.)
for Root,subdirs,files in Os.walk (dir):
to name in Files:
; oldname = name
newname = Re.sub (regex,f,name)
print ("Before:" + os.path.join (root,oldname))
& nbsp; print ("after : " + os.path.join (root,newname))
if not name = = NewName and not os.path.exists (Os.path.join (root,newname)):
& nbsp; Os.rename (Os.path.join (Root,oldname), Os.path.join (root,newname))
for Dir In Subdirs:
rename_dir (Os.path.join (root,dir))
Rename_dir ("C:\\python31\\test", "\[.*\] (. *) \[www.jb51.net\] (. *)", Lambda M:m.group (1) +m.group (2))
It's written in Perl, and it's not much less than the code.
Copy Code code as follows:
Use strict;
Use warnings;
Use File::find;
My $regex = "\\[.*\\] (. *) \\[www.jb51.net\\] (. *)";
# $replace doesn ' t work
My $replace = "\$1\$2";
Sub wanted {
My $name = $File:: find::name;
if (-f $name) {
my $newname = $name;
$newname =~ s/$regex/$1$2/;
Print "Before: $File:: find::name\n";
Print "After: $newname \ n";
if (!-e $newname) {
Rename ($name, $newname);
}
}
}
Sub rename_dir{
My ($dir,) = @_;
if (!-d $dir | |!-e $dir) {
Print "The input is not directory" or "exist";
}
Find (\&wanted, $dir);
}
&rename_dir ("C:\\perl\\test");
Perl Implementation 2
Copy Code code as follows:
Use strict;
Use warnings;
My $regex = "\\[.*\\] (. *) \\[www.jb51.net\\] (. *)";
# $replace doesn ' t work
My $replace = "\$1\$2";
Sub rename_dir{
my $dir = shift;
if (!-d $dir | |!-e $dir) {
Print "The input is not directory" or "exist";
}
Opendir (DIR, $dir) | | Die "Cannot opendir $dir."
foreach (Readdir (DIR)) {
if ($_ eq '; ' | | $_ eq ' ... ') {Next;}
My $name = $dir. '/'. $_;
if (-D $name) {
Rename_dir ($name);
Next
}
My $newname =$_;
$newname =~ s/$regex/$1$2/;
$newname = $dir. '/'. $newname;
Print "Before: $name \ n";
Print "After: $newname \ n";
Rename ($name, $newname);
}
#closedir (DIR);
}
&rename_dir ("C:\\perl\\test");