Trimming characters from filename script help

applescriptjavascriptrename

I'm trying to execute a pretty simple renaming script, but am unable to do so with an Automator workflow and my scripting knowledge is totally inadequate (this is ultimately for use with Hazel). The equivalent that I'm trying to execute in Name Mangler is to:

'remove 2 characters starting at index 1 – counting from start'

and

'remove 2 characters starting at index 2 – counting from end'

Any assistance would be appreciated; AppleScript, Java and Shell are all fine as this will be embedded in Hazel.

Best Answer

UPDATE: I misread your question and originally gave an answer that started at "character 1." If I understand correctly you want to trim off the first two characters, and the last two. Therefore, you want to start at "character 3." I have made the correction here.

Do it this way:

set the_short_name to characters 3 thru -2 of the_original_name as string

That's all there is to it.

Since you're working with Hazel you can get the name of the file this way:

set the_original_name to name of theFile

You may want to pull off more than just two characters since the last four characters are probably ".png" so take off 6 characters, and then add ".png" to the short name.

One more thing: Hazel may think that the renamed file is a "new" file, and consequently run the AppleScript on the renamed file over and over until the name is so short it can't get shorter. The way I'd handle that is I'd move the file out of the watched folder first, and rename it after that. In my case I have a folder called "Renamed Screenshots" on my desktop-- your path is going to be different. Use your own username (not "youruser" as I've put in the line below).

move theFile to (POSIX file "/Users/youruser/Desktop/Renamed Screenshots")
        set the name of theFile to the_short_name & ".png"

That should do it.