Search code examples
vbscriptntfs

Is there a way to move strings around in filenames? (VisualBasic)


So my context is that I have a multiple folders FULL of files sorted alphabetically. Now, in the English world there is a pesky little article named "the", which isn't very significant, and throws your auto-sorting off. Now what I WANT to do is move "the" to the end of a filename, but before one of my suffixes (e.g. -01, -02) because multiple files have the same name but are different versions. So something like this:

"The Exemplar Example-01.ex" --> "Exemplar Example, The-01.ex"

So I turned to VisualBasic Script (VBS) and got close to what I wanted by searching Google, but couldn't get what I wanted exactly. Here's my script:

private directfold
directfold=InputBox("Please specify a directory path:")
MsgBox("The folder to be 'de-annnoyed' is: " & directfold)

public annoyance
annoyance = "the"

Set fso = CreateObject("Scripting.FileSystemObject")  
Set folder = fso.GetFolder(directfold)

For each file In folder.Files    

If instr(file.name, searchFileName) = 1 Then
    file.name = renameFileTo

So at the bottom of the script you may find the "renameFileTo" command is given no argument because I do not want to rename the entire file, I want to "move around" a part of the filename, if that part of the filename matches the "annoyance" string ("the"). So after my long ramble, can anyone offer me any help?


Solution

  • You may want to make the annoyance word include the trailing space so names like "They" or "Theme" etc won't trigger it.

    If the delimiter at the end is always - and is the only instance of the character in the string, you can use Replace to replace the string. Something like this

    annoyance = "The "
    f = "The Exemplar Example-01.ex"
    newName = Replace(Replace(f,"-",", " + Trim(annoyance) + "-"),annoyance,"")
    

    newName will equal Exemplar Example, The-01.ex

    The inner Replace will replace the - character according to how you format it, and the outer will replace the annoyance word with nothing. Trim will remove the trailing space.

    edit: If you only want to replace one occurrence of the string, use the following:

    newName = Replace(Replace(f,"-",", " + Trim(annoyance) + "-"),annoyance,"",1,1)
    

    See here for additional info on the Replace function.