Home > Back-end >  Exchange filename position
Exchange filename position

Time:09-17

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.

CodePudding user response:

SO is not a code-writing service; that said: you could use AppleScript (scripting Finder/System Events to traverse the files and text item delimiters to split up each file name), or you could do it with a shell script, which has the advantage of being much quicker:

#!/bin/sh

for f in /path/to/input/folder/*; do
    n=`basename "$f" | awk -F '.' '{ print $4"."$2"."$5"."$6"."$3"."$1".pdf" }'`
    mv "$f" "/path/to/output/folder/$n"
done

CodePudding user response:

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
  • Related