Script to Clean Filenames with a set of rules

Looking for guidance:

I'm trying to create a script to clean filenames with a set of rules. I've been having ChatGPT help me with the scripting which has been usually helpful but it's stuck with this one.

Here are the rules:

I need a directory opus button that will clean the selected filenames with these rules:

Allow only these characters:

  • A-Z
  • a-z
  • 0-9
  • &.-
  • Spaces

Characters should be replaced as follows:

_ should be replaced with a space

“ should be removed

() should be removed

, should be replaced with a period

Any other character not listed should be replaced with a period.

It gave me this script which is not working.

@script vbscript
Option Explicit
Function OnGetNewName(ByRef getNewNameData)
    Dim strFileName, strExtension, strReplacedName, strPattern

    ' Get the original filename
    strFileName = getNewNameData.item.name_stem
    strExtension = getNewNameData.item.ext

    ' Replace characters according to the rules
    strReplacedName = Replace(strFileName, "_", " ")
    strReplacedName = Replace(strReplacedName, Chr(34), "") ' Remove quotation marks
    strReplacedName = Replace(strReplacedName, "(", "") ' Remove left parenthesis
    strReplacedName = Replace(strReplacedName, ")", "") ' Remove right parenthesis
    strReplacedName = Replace(strReplacedName, "[", "") ' Remove left bracket
    strReplacedName = Replace(strReplacedName, "]", "") ' Remove right bracket
    strReplacedName = Replace(strReplacedName, ",", ".") ' Replace commas with periods

    ' Replace all other characters not in the allowed list with a period
    strPattern = "[^A-Za-z0-9 &.-]"
    strReplacedName = ReplaceCharsWithPeriod(strReplacedName, strPattern)

    ' Combine the cleaned name with the original extension
    OnGetNewName = strReplacedName & strExtension
End Function

Function ReplaceCharsWithPeriod(str, pattern)
    Dim regex, matches, match, i
    Set regex = new RegExp
    regex.Global = True
    regex.IgnoreCase = False
    regex.Pattern = pattern
    Set matches = regex.Execute(str)
    For i = matches.Count - 1 To 0 Step -1
        Set match = matches(i)
        str = Left(str, match.FirstIndex) & "." & Mid(str, match.FirstIndex + match.Length + 1)
    Next
    ReplaceCharsWithPeriod = str
End Function

When I try to run the script from a button nothing happens. No error, nothing. I'm thinking I don't have the script setup right. Here's how the button looks. Any guidance would be most appreciated.

1 Like

Thanks leo! That 3rd one was perfect.

1st one off this post of mine would also serve you well, it is not only a template for extensible renaming but handles tricky chars in downloaded files as well.

Please share your workable Script with us.