Search code examples
automationapplescriptfilenamesrenamefinder

Applescript for changing filenames


I would like to change thousand of filenames with an applescript.

The filenames are all made in this way:

firstPart - secondPart XX.xxx

with the XX a certain number and the .xxx either a jpg or a png extension.

I would like to simply change the parts around so that it would become:

secondPart - firstPart XX.xxx

I have come up with this but my codings skills fail me.

tell application "Finder" to set aList to every file in folder "ImageRename"
set text item delimiters to {" - ", "."}
repeat with i from 1 to number of items in aList
    set aFile to (item i of aList)
    try
        set fileName to name of aFile
        set firstPart to text item 1 of fileName
        set secondPart to text item 2 of fileName
        set thirdPart to text item 3 of fileName
        set newName to secondPart & " - " & firstPart & "." & thirdPart
        set name of aFile to newName
    end try
end repeat

This works only the number sticks to the second part. So it becomes:

SecondPart XX - firstPart.xxx

How can I make two integers as a text item delimiter?

Please help me out and teach me along the way :-)


Solution

  • Just use the space as the delimiter and build the parts. Edited: to allow for spaces in the text parts.

    tell application "Finder" to set aList to every file in folder "ImageRename"
    set AppleScript's text item delimiters to " "
    repeat with i from 1 to number of items in aList
        set aFile to (item i of aList)
        try
            set fileName to name of aFile
            set lastParts to text item -1 of fileName
            set wordParts to (text items 1 thru -2 of fileName) as string
            set AppleScript's text item delimiters to " - "
            set newName to {text item 2 of wordParts, "-", text item 1 of wordParts, lastParts}
            set AppleScript's text item delimiters to " "
            set name of aFile to (newName as string)
        end try
    end repeat
    set AppleScript's text item delimiters to ""