如何用AppleScript创建按文件名首字母分类的Folder Action?
Hey there! I see you're trying to get your Folder Action to sort new files into subfolders based on their first letter, but it's dumping everything into the "A" folder right now. Let's break down what's going wrong and fix it.
The issue with your initial attempt (set DestinationFolderName to text 1 thru 1 of filename) is probably that you're not correctly accessing the actual filename string of the item. Let's adjust how you grab the filename and extract its first character properly.
Here's a working script that does exactly what you need:
on adding folder items to this_folder after receiving added_items repeat with this_item in added_items -- Get the filename of the item (without the full path) set item_name to displayed name of (info for this_item) -- Extract the first character, convert to uppercase (so "apple" and "Apple" go to the same folder) set first_char to text 1 thru 1 of item_name set target_folder_name to uppercase of first_char -- Build the full path to the target subfolder set target_folder to this_folder & target_folder_name as string -- Create the folder if it doesn't already exist tell application "Finder" if not (exists folder target_folder) then make new folder at this_folder with properties {name:target_folder_name} end if -- Move the file to the target folder move this_item to folder target_folder end tell end repeat end adding folder items to
Let's walk through the key fixes:
- Getting the filename correctly: Using
displayed name of (info for this_item)ensures we get the actual visible name of the file, not just a path reference. - Consistent casing: Converting the first character to uppercase (with
uppercase of first_char) prevents duplicate folders for uppercase and lowercase starting letters (e.g., no separate "a" and "A" folders). - Folder existence check: The script checks if the target folder exists before trying to move the file—if it doesn't, it creates it automatically.
Why your initial attempt failed:
When you tried text 1 thru 1 of filename, you were likely referencing a file object instead of a string. You need to explicitly pull the name as a string first (which the displayed name line does) before you can slice its characters.
To use this script:
- Open Automator on your Mac
- Create a new Folder Action
- Select the folder you want to apply this to
- Delete any default actions, then add a Run AppleScript action
- Replace the default code with the script above
- Save the Folder Action (it'll be stored in
~/Library/Workflows/Folder Actions/)
Test it by dropping a few files with different starting letters into your target folder—they should automatically move to the correct subfolders!
内容的提问来源于stack exchange,提问作者Alastair Farman

