Finder - Create Subfolders and Move Files with Applescript

applescriptfinder

I'm trying to organize a bunch of audiobooks and would like to automate some of the work. I have just very basic knowledge of Applescript, but I can usually find a scriptlet online to do the work I want. This one I haven't gotten to work yet.
My files are like this:

Books/Author1/Book.mp3

Books/Author2 – Book.mp3

Books/Author3/Book.mp3

What I want to do is select the books that are not in an Author subfolder, create a subfolder with the Author name, rename the file to just the book title and finally move the book into the newly created folder. I have tried the following script and it works partly. It does everything except move the file at the end. It gives me an error saying: "error "Finder got an error: Handler can’t handle objects of this class." number -10010". Is there any way to change it so it will work? If it makes any difference, the files are on an attached drive (smb://NAS._smb._tcp-local/Audiobooks/Books). There are probably syntax errors for any purists, but as long as it works, I'm not picky 🙂

tell application "Finder"
    set selectedFiles to selection as alias list
    
    set containingFolder to container of item 1 of selectedFiles as alias
    
    repeat with f from 1 to count of selectedFiles
        set thisItem to item f of selectedFiles
        set oldName to thisItem's name
        
        set newFolderName to text 1 thru ((get offset of "-" in oldName) - 2) of oldName
        set newFileName to text ((get offset of "-" in oldName) + 2) thru end of oldName
        
        set name of thisItem to newFileName
        
        move newFileName to (make new folder at containingFolder with properties {name:newFolderName})
    end repeat
end tell

Best Answer

I would use the shell in such a case.

Open Terminal and enter cd path/to/Audiobooks/Books, then run

find . -type f -name '* - *' -maxdepth 1 \
    -exec bash -c 'mkdir -p "${1%% - *}"; mv "$1" "${1%% - *}/${1#* - }"' _ {} \;

PS: This assumes that you want to move all files in that folder and that Author and Title are always separated by - .


This uses find to find all matching (-name '* - *') files (-type f) in the current directory (-maxdepth 1) and then executes the bash ... \; part on each of them. The executed part is basically a bash script which gets the filename in $1 and then uses text substitution to extract author and title (${1%% - *} cuts off the part starting with -, ${1#* - } cuts of the part ending with it).