有人可以建议一个脚本来重命名Windows子目录中的一堆文件,这些文件名具有带下划线的空格。例如,如果文件名是用于重命名Windows子目录中的文件的脚本
abc xyz.pdf
应该
abc_xyz.pdf
有人可以建议一个脚本来重命名Windows子目录中的一堆文件,这些文件名具有带下划线的空格。例如,如果文件名是用于重命名Windows子目录中的文件的脚本
abc xyz.pdf
应该
abc_xyz.pdf
Perl:使用File::Find
对文件进行递归查找和操作。
请注意,您需要小心:不要重命名具有下划线的DIRECTORIES,因此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?
}
下面的批处理文件没有测试,但应该工作。
@echo off
for %%i in (*) do call :rename "%%~ni"
goto :EOF
:rename
set filename=%1
set newname=%filename: =_%
rename "filename" "newname"
这是VBSCript脚本。它会在文件夹C重命名文件:\测试
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
我还在学习PERL所以参加了这个刺...
opendir (curDir, ".");
@filesWithSpaces = grep(/.*\s.*\..*/, readdir (curDir));
foreach $oneFile (@filesWithSpaces){
$newName = $oneFile;
$newName =~ s/\ /_/g;
print "RENAMING: $oneFile -> $newName \n";
rename($oneFile, $newName);
}
看起来我最初的测试罚款。它不是递归的。
这是一个有效的VBScript。但它不会递归到指定目录的子目录中。
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
是否需要递归到子目录的子目录中? – Casey 2011-01-12 04:33:31
是的递归到一个目录 – iceman 2011-01-12 06:48:18
如果任何子目录名称中有空格,会发生什么?保持原样?或重命名?如果重命名,我认为PARENT目录空间不应该重命名?例如。如果你从`C:\ my docs \ pdfs`开始,并且有一个文件`C:\ my docs \ pdfs \ sci fi \ star wars1.pdf`,它应该以`C:\ my docs \ pdfs \ sci fi \ star_wars1.pdf`,`C:\ my docs \ pdfs \ sci_fi \ star_wars1.pdf`或`C:\ my_docs \ pdfs \ sci_fi \ star_wars1.pdf`?我假设#1。 – DVK 2011-01-12 13:20:11