用于重命名Windows子目录中的文件的脚本

时间:2011-01-12 04:24:33

标签: perl vbscript

有人可以建议一个脚本来重命名Windows子目录中的一堆文件,文件名中包含带下划线的空格。例如,如果文件名是

abc xyz.pdf

应该是

abc_xyz.pdf

5 个答案:

答案 0 :(得分:1)

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?
}

答案 1 :(得分:0)

以下批处理文件未经过测试,但应该可以使用。

@echo off
for %%i in (*) do call :rename "%%~ni"
goto :EOF

:rename
set filename=%1
set newname=%filename: =_%
rename "filename" "newname"

答案 2 :(得分:0)

这是VBSCript脚本。它将重命名文件夹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

答案 3 :(得分:0)

我还在学习PERL,所以在这... ...

opendir (curDir, ".");

@filesWithSpaces = grep(/.*\s.*\..*/, readdir (curDir));

foreach $oneFile (@filesWithSpaces){
  $newName = $oneFile;
  $newName =~ s/\ /_/g;
  print "RENAMING: $oneFile -> $newName \n";
  rename($oneFile, $newName);

}

我的初步测试看起来很好。但它不是递归的。

答案 4 :(得分:0)

这是一个有效的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