从Directory中的列表重命名单个文件

时间:2013-03-09 11:39:59

标签: vbscript batch-file cmd

请原谅我的编程无知。这就是天才存在的原因!

我想通过Sched任务每隔30分钟重命名一个文件。

文件列表:

test1.txt的 的test2.txt test3.txt 等..

分为: 的test.txt 的test2.txt text3.txt 等..

test.txt将被程序删除。因此,在30分钟的时间内,我希望将test2.txt重命名为test.txt,依此类推,直到所有文件都被处理完毕。

感谢您的帮助。找到Rename different files to one file name, one at a time但它只复制文件。

1 个答案:

答案 0 :(得分:2)

您可以检查具有给定basename的文件是否存在,否则重命名具有附加到basename的最小编号的文件。尝试这样的事情:

Const basename  = "test"
Const srcFolder = "..."
Const extension = "txt"

Set fso = CreateObject("Scripting.FileSystemObject")

dstFile = fso.BuildPath(srcFolder, basename & "." & extension)

If fso.FileExists(dstFile) Then WScript.Quit 0  'nothing to do

For Each f In fso.GetFolder(srcFolder).Files
  If LCase(fso.GetExtensionName(f.Name)) = extension Then
    If LCase(Left(f.Name, Len(basename))) = basename Then
      num = Mid(fso.GetBaseName(f.Name), Len(basename)+1)
      If Len(num) > 0 Then
        num = CInt(num)
        If IsEmpty(minnum) Or minnum > num Then minnum = num
      End If
    End If
  End If
Next

If Not IsEmpty(minnum) Then
  srcFile = fso.BuildPath(srcFolder, basename & minnum & "." & extension)
  fso.MoveFile srcFile, dstFile
End If

通过对正则表达式进行测试,可以简化对文件名和数字的检查:

Set re = New RegExp
re.Pattern    = "^" & basename & "(\d+)\." & extension & "$"
re.IgnoreCase = True

For Each f In fso.GetFolder(srcFolder).Files
  Set m = re.Execute(f.Name)
  If m.Count > 0 Then
    num = CInt(m(0).SubMatches(0))
    If IsEmpty(minnum) Or minnum > num Then minnum = num
  End If
Next