Developer by Blood
Developer by Blood

Reputation: 165

Search a file having particular string in its name and rename it

I am amateur to VBScript (and quite fascinated with the way it works ;)). I have to work on certain reports on daily basis for which I have generated a script to do the task. The trouble is that I have generated that script for particular name of file and these reports daily come with the timedate and few extra parameters added to them in the name. So, I need a vbscript to save my 10 mins of daily work of renaming the files according to the name specified in script.

For e.g. D:/reports/ have file AMR KilobyteData_23022013_4399_223.xls I want to rename it to just AMR KilobyteData.xls. Thats it ! :)

Please help me with the issue :)

Upvotes: 2

Views: 35793

Answers (2)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200573

Does the information you want to remove always come after the first underscore in the file name? If so, you could do something like this:

Set fso = CreateObject("Scripting.FileSystemObject")

For Each f In fso.GetFolder("D:\reports").Files
  pos = InStr(f.Name, "_")
  If pos > 0 Then
    newName = Left(f.Name, pos-1) & "." & fso.GetExtensionName(f.Name)
    f.Move fso.BuildPath(f.ParentFolder, newName)
  End If
Next

Upvotes: 2

AutomatedChaos
AutomatedChaos

Reputation: 7490

First iterate through all files in your folder using a script like this:

Dim fso, folder, file
Dim folderName, searchFileName, renameFileTo

' Parameters
folderName     = "D:\reports\"
searchFileName = "AMR KilobyteData"
renameFileTo   = "AMR KilobyteData.xls"

' Create filesystem object and the folder object
' how the FSO works: http://msdn.microsoft.com/en-us/library/2z9ffy99(v=vs.84).aspx
Set fso = CreateObject("Scripting.FileSystemObject")  
Set folder = fso.GetFolder(folderName)  

' Loop over all files in the folder until the searchFileName is found
For each file In folder.Files    
    ' See if the file starts with the name we search
    ' how instr works: http://www.w3schools.com/vbscript/func_instr.asp
    If instr(file.name, searchFileName) = 1 Then
        file.name = renameFileTo
        ' Exit the loop, we only want to rename one file
        Exit For
    End If
Next

It should function correctly (but I did not test it). I hope I triggered your curiosity and you will look into the mechanisms how this code works. That is why I put in the links where documentation can be found.

Upvotes: 2

Related Questions