脚本将文件名的前3个字符移动到最后

时间:2013-05-21 16:06:37

标签: vbscript rename wsh

我有一个目录,里面装满了我需要重命名的文件。对于每个文件,我需要获取文件名的前三个字符,并将它们移动到扩展名之前的文件名末尾。 所以003999999.wav将成为999999003.wav。

脚本语言并不重要。它只需要在Windows中工作。这似乎是一个使用vbscript的简单脚本,我现在正在做一些阅读,但想到我会看到有人已经有这样的东西可以工作。

编辑 - 所以我想我已经找到了如何做到这一点,除了获取文件名字符的部分。这就是我所拥有的。

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder("C:\Directory")


For Each strFile in objFolder.Files
arrNames = Split(strFile.Name, ".")
If arrNames(1) = "mp3" Then

    Set objstart = objFSO.Range(0,3)
    Set objend = objFSO.Range(4,17)
    strNewName = "C:\Directory\" & objend.Text & objstart.Text & ".mp3"

    objFSO.MoveFile strFile.Path, strNewName
End If
Next

3 个答案:

答案 0 :(得分:0)

试试这个脚本。我使用简单的字符串函数来操作每个文件名。

'Rename Files
'============
Dim objFSO, objFolder, strFile, intLength, firstThree, restofName, strNewName

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder("C:\Directory")

For Each strFile in objFolder.Files

    'Get files by extension
    If objFSO.GetExtensionName(strFile.Name) = "mp3" Then

        'Use instr to get the location of the "." and subtract 1 for the "."
        intLength = InStr(1,strFile.Name,".",1)-1

        'Use the Left function to get the first three characters of the filename
        firstThree = Left(strFile.Name,3)

        'Use the Mid function to get the rest of the filename subtract 3 for the file extension
        restofName = Mid(strFile.Name,4,intLength -3)

        strNewName = "C:\Directory\" & restofName & firstThree & ".mp3"
        objFSO.MoveFile strFile.Path, strNewName

    End If
Next

WScript.Echo "Done!"

答案 1 :(得分:0)

使用正则表达式代替虚构的.Range方法:

>> s1 = "003999999.wav"
>> Set r = New RegExp
>> r.Pattern = "(\d{3})(\d+)(\.wav)"
>> s2 = r.Replace(s1, "$2$1$3")
>> WScript.Echo s2
>>
999999003.wav

剪切三位数(\ d {3}),其他数字(d +)和(转义)点后跟输入字符串中的扩展名(wav)并重新排列.Replace中的3个部分

答案 2 :(得分:0)

简化版JP's solution

Set fso = CreateObject("Scripting.FileSystemObject")
For Each f In fso.GetFolder("C:\Directory").Files
  extension = fso.GetExtensionName(f.Name)
  If LCase(extension) = "mp3" Then
    basename = fso.GetBaseName(f.Name)
    f.Name = Mid(basename, 4) & Left(basename, 3) & "." & extension
  End If
Next

批处理你会这样做:

@echo off

setlocal EnableDelayedExpansion

for %%f in (C:\Directory\*.mp3) do (
  set basename=%%~nf
  ren "%%~ff" "!basename:~3!!basename:~0,3!%%~xf"
)

endlocal