【问题标题】:Rename single file from list in Directory重命名目录列表中的单个文件
【发布时间】:2023-03-19 22:00:02
【问题描述】:

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

我想通过计划任务每​​ 30 分钟重命名一个文件。

文件列表:

test1.txt test2.txt test3.txt 等等……

进入: 测试.txt test2.txt text3.txt 等等……

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

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

【问题讨论】:

    标签: vbscript batch-file cmd


    【解决方案1】:

    您可以检查具有给定基本名称的文件是否存在,否则将使用附加到基本名称的最小数字重命名文件。试试这样的:

    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
    

    【讨论】:

    • 感谢您的及时回复!这一行似乎有错误 num = Mid(fso.GetBaseName(f.Name), Len(basename)+1))
    • 抱歉。预期的语句结束。第 14 行字符 58
    • 好的,它适用于文本文件,但是 zip 扩展名和 BULK_LOAD 的基本名称怎么样。在这种情况下,下划线是否存在问题?
    • 下划线没问题。 Zip 可能被视为文件夹而不是对象,这是正确的吗?
    • @user2151337 不,zip 文件仍然是文件,并被视为此类文件。当然,您需要将常量extension"txt" 更改为"zip"。正如您已经发现的那样,下划线不是问题。该脚本查看具有给定extension 的文件,其名称以给定basename 开头,后跟任意位数。有什么特别的事情没有按预期工作吗?
    猜你喜欢
    • 2019-09-19
    • 2012-12-27
    • 1970-01-01
    • 2020-07-03
    • 2015-10-08
    • 2018-08-29
    • 1970-01-01
    • 2018-11-01
    • 1970-01-01
    相关资源
    最近更新 更多