Search code examples
macosapplescriptautomator

Exchange filename position


I want to exchange hundreds of filename positions of a file in FolderX.

The file names are all created on this way: pos1.pos2.pos3.pos4.pos5.pos6.pdf example: (GK.19.kkla.0715.nr.36053342.zg.119.pdf)

I would like to exchange some positions so that it changes to: pos4.pos2.pos5.pos6.pos3.pos1.pdf

As an example, a command such as; exchange pos3->pos6 or pos1->pos4

I looked in the Automator, but it can only add before or after file names, but no positions exchange.

maybe AppleScript? Thanks for inputs.


Solution

  • The following solution uses AppleScript's text item delimiters and System Events. It is quite fast, and has the advantage of avoiding throwing an error when the filename of some file in a folder does not match the desired pattern. Also, it works with pdfs of the folder.

    set folderHFS to (choose folder) as text
    
    set {ATID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, "."}
    tell application "System Events"
        repeat with aFile in (get files of folder folderHFS whose name extension is "pdf")
            try
                set {pos1, pos2, pos3, pos4, pos5, pos6, ext} to text items of (get name of aFile)
                set name of aFile to {pos4, pos2, pos5, pos6, pos3, pos1, ext} as text
            end try
        end repeat
    end tell
    set AppleScript's text item delimiters to ATID