MacOS – Automator/Applescript using Tags

applescriptautomatormacmacos

I need an Automator/Applescript to move a file to a certain folder based on a specific tag it contains. The input would be the file. Anybody have any ideas?

TIA, Jake

Best Answer

This should do the trick:

property parentfolder : path to home folder
set theFiles to choose file default location (POSIX path of parentfolder) with multiple selections allowed
repeat with theFile in theFiles
    set the_tags to paragraphs of (do shell script "mdls -raw -name kMDItemUserTags " & quoted form of POSIX path of theFile & " |sed 's/[()]//g' | tr -d '\\n' | tr -d ' '| tr -d '\"' | sed 's/u\\\\U0308/ΓΌ/g'")
    if the_tags does not contain "null" then
        tell application "Finder"
            set parentfolder to folder of theFile as text
            if not (((parentfolder as text) & item 1 of the_tags) exists) then
                make new folder at parentfolder with properties {name:item 1 of the_tags}
            end if
            move theFile to (parentfolder & item 1 of the_tags)
        end tell
    end if
end repeat

This Script will move every file with a specific Tag to a folder with the same name as the tag. This can be changed with several if clauses before "move theFile".