MacOS – Using AppleScript to delete select files in a folder

applescriptmacos

I have duplicate photos in a folder. (Thousands of them.) Their names are all Xxxxx (1).jpg. I'd like to automate their deletion but haven't hit on the correct syntax. I've been trying variants on the below and getting a variety of errors. Thanks very much for any suggestions!

tell application "Finder"

    delete (every item of folder {macintosh hd / users / mike / documents / OneDrive / Pictures} whose name contains "(1)")

end tell

For example, the error from the above was…

Expected “,” or “}” but found identifier.

Best Answer

The reason you're getting Expected “,” or “}” but found identifier. is because you have a malformed list for the path. You cannot define the path like {macintosh hd / users / mike / documents / OneDrive / Pictures}.

Use the following instead:

tell application "Finder"
    delete (every item of folder "Macintosh HD:Users:mike:Documents:OneDrive:Pictures" whose name contains "(1)")
end tell

Depending on how may files there are to delete, Finder can have trouble running this AppleScript script, from taking far too much time and or the process stalling without recovery, to then require a Force Quit.

Personally, I would not use AppleScript and instead just use Terminal, and change directory to the one containing all the files and use rm *\(1\)* to delete all files containing (1). However use the rm command with great care because all deleted files are final!