Script to rename files in a Windows subdirectory
Can someone suggest a script to rename a bunch of files in a Windows subdirectory with filenames having spaces to them having underscores. For example 开发者_开发问答if the filename is
abc xyz.pdf
It should be
abc_xyz.pdf
Perl: Use File::Find
for recursive finding and actioning on files.
Please note that you need to be careful about: Don't rename DIRECTORIES that have underscore, thus File::Basename
.
use File::Find;
use File::Basename;
use File::Spec;
use strict;
find ({ 'wanted' => \&renamefile }, 'X:\my\sub\dir');
sub renamefile {
my $file = $_;
return unless (-f $file); # Don't rename directories!
my $dirname = dirname($file); # file's directory, so we rename only the file itself.
my $file_name = basename($file); # File name fore renaming.
my $new_file_name = $file_name;
$new_file_name =~ s/ /_/g; # replace all spaces with underscores
rename($file, File::Spec->catfile($dirname, $new_file_name))
or die $!; # Error handling - what if we couldn't rename?
}
The following batch file isn't tested, but should work.
@echo off
for %%i in (*) do call :rename "%%~ni"
goto :EOF
:rename
set filename=%1
set newname=%filename: =_%
rename "filename" "newname"
Here is the VBSCript script. It will rename files in the folder C:\Test
Dim fso, f, f1, fc, s Set fso = CreateObject("Scripting.FileSystemObject") Set f = fso.GetFolder("C:\Test") Set fc = f.Files For Each f1 in fc f1.move f1.ParentFolder & "\" & replace(f1.Name, " ", "_") Next
Im still learning PERL so took a stab in this...
opendir (curDir, ".");
@filesWithSpaces = grep(/.*\s.*\..*/, readdir (curDir));
foreach $oneFile (@filesWithSpaces){
$newName = $oneFile;
$newName =~ s/\ /_/g;
print "RENAMING: $oneFile -> $newName \n";
rename($oneFile, $newName);
}
Looks fine on my initial tests. Its not recursive though.
Here is a working VBScript. It does not recurse into subdirectories of the specified directory however.
Dim fso
Dim folder
Dim stringToFind
Dim replacement
' Check arguments
If Wscript.Arguments.Count <> 3 Then
' Usage
Wscript.echo "Usage: rename.vbs folder string_to_find replacement"
WScript.Quit
End If
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder(WScript.Arguments(0))
If Err.Number <> 0 Then
WScript.Echo "Folder " & WScript.Arguments(0) & " does not exist."
WScript.Quit
End If
stringToFind = WScript.Arguments(1)
replacement = WScript.Arguments(2)
For Each file in folder.Files
fso.MoveFile file.ParentFolder & "\" & file.Name, file.ParentFolder & "\" & Replace(file.Name, stringToFind, replacement)
Next
Set folder = Nothing
Set fso = Nothing
精彩评论