AppleScript to move files to correct location - applescript

Goal:
I am trying to write a script that I can tie into a folder action to move files from a download folder to the proper location. The folder will see music, movies and TV shows, or sports. There will be individual files as well as folders of multiple items. I have the skeleton of the script done, but I'm struggling with a few things that I know how to do in other languages.
Parameters:
TV: S%%E%% for individual files & S%% for folders
Movies: Folders with a single video file(mkv, mp4, m4v) and no S%%E%% in name, or folders without S%%
Audio: File type (mp3, aac, flac, wav) for individual files, folders will be tough seeing the contents
Issues:
How do I change the file selection to include folders and files for testing? I think this will work fine when I am giving the script input from a folder action in Automator, but not entirely sure yet.
It seems there are not wildcards available in Applescript to use in my comparisons.
My main issue is not knowing how to open a folder item and loop through the contents looking for certain extensions or names.
GitHub:https://github.com/wiebs2334/DownloadManager
Any suggestions or advice would be very much appreciated!

Vanilla AppleScript is not able to handle wildcards for text search but there is a free Scripting Addition Satimage.osax which adds powerful functions for example find text with Regular Expression
You can find the OSAX on the Smile Companion OSAX site. Download Satimage osax 3.7.0 (build 411) and put the file into /Library/ScriptingAdditions (top level Library!)
This is your optimized script using the Scripting Addition, the basic regex patterns are
"\\.S\\d{2}E": Look for a dot follows by capital S followed by two digits and a captital E
"(nhl|nfl|ncaa)" : Text contains "nhl" or "nfl" or "ncaa"
If the text doesn't match the pattern an error is thrown.
The major changes are
The run handler shows a dialog to select files or folders
The open handler is added to use the script as droplet
Your if/end if - if/end if expressions are replaced with if/else if/end if
If your are going to use the script as folder action both files and folders are considered anyway
property audioKeywords : {"mp3", "aac", "flac", "wav"}
property videoExtensions : {"mkv", "m4v", "mov", "mp4"}
on run
set {button returned:buttonReturned} to display dialog "Choose files or folders" buttons {"Cancel", "Choose Files", "Choose Folders"}
if buttonReturned is "Choose Files" then
classifyItems for (choose file with multiple selections allowed)
else
classifyItems for (choose folder with multiple selections allowed)
end if
end run
on open theItems
classifyItems for theItems
end open
to classifyItems for myFiles
repeat with anItem in myFiles
set anItem to anItem as text
set isVideo to false
set isTV to false
set isMovie to false
set isAudio to false
set isSports to false
tell application "System Events" to set {theClass, theName, theExt, theContainer} to {class, name, name extension, container} of disk item anItem --set variables
set className to theClass as text
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&& Files &&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
if className is "file" then
########### Video ############
if theExt is in videoExtensions then --search through all video extensions
set isVideo to true
########### TV ############
try
find text "\\.S\\d{2}E" in theName with regexp
set isTV to true
on error
########### Sports ############
try
find text "(nhl|nfl|ncaa)" in theName with regexp
set isSports to true
on error
########### Movies ############
set isMovie to true
end try
end try
########### Audio ############
else if theExt is in audioKeywords then
set isAudio to true
end if
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&& Folders &&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
else if className is "folder" then
########### TV ############
try
find text "\\.S\\d{2}\\." in theName with regexp
set isTV to true
on error
try
########### Audio ############
find text "(mp3|aac|flac|wav)" in theName with regexp
set isAudio to true
on error
########### Movie ############
set isMovie to true
end try
end try
end if
display dialog ("Type:" & theClass & " || Ext:" & theExt & " || Video:" & isVideo & "
" & theName & "
Movie:" & isMovie & " || TV:" & isTV & " || Sports:" & isSports & "
Audio:" & isAudio)
end repeat
end classifyItems

Related

Applescript Droplet - Export Image Resolution of All Files in Folder/Subfolder as text file

I'm probably making a simple error but I can't seem to get my code to work properly. Figure I'd ask the geniuses on this site for help. I'm a novice scripter, more like code piecer. This is my first post, please be gentle.
What I'm trying to do... I have a folder (and subfolders) full of images. I'd like to have a applescript droplet that I can drag this folder on this droplet to get a text file report of the resolution and path of that image. This way I can insure my files are all the same and correct resolution prior to sending to my end vendor. And if the file isn't the correct resolution, I have the path to which file needs to be adjusted. I was able to create a droplet that could handle individual files, but once I drag a folder of images and sub-folders, I just get a blank text document.
This is what my initial results look like in a text file for files:
72.0 dpi /Users/chewbacca/Desktop/untitled folder/pixels-300x232 copy 2.png
72.0 dpi /Users/chewbacca/Desktop/untitled folder/pixels-300x232 copy 3.png
72.0 dpi /Users/chewbacca/Desktop/untitled folder/pixels-300x232 copy 4.png
Here's my attempt at getting the folder/sub-folder droplet to work:
on open (rawList)
set outFile to (choose file name with prompt "Output file:" default name "ResolutionReport.txt")
open for access outFile with write permission
set fileList to every file of rawList
repeat with i from 1 to number of items in fileList
tell application "Image Events"
launch
set thisImage to open file (oneFile as string)
copy the resolution of thisImage to {H_res, V_res}
close thisImage
end tell
write (H_res as string) & " dpi " & (POSIX path of oneFile) & return to outFile
end repeat
close access outFile
end open
I realize that this could be more simple in perl, but I'd like to keep this pure Applescript for now since I'm starting to grasp how this language is used.
Really helpful are the templates (menu File) and code-snippets (CTRL-Click into a script).
The template Droplets->Recursive Image File Processing Droplet provides everything. Here an edited version that does what you want:
(*
Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in this original Apple software ( the "Apple Software" ), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and / or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON - INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES ( INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION ) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND / OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT ( INCLUDING NEGLIGENCE ), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Copyright ( C ) 2011 Apple Inc. All Rights Reserved.
*)
(* INSTRUCTIONS
This droplet is designed to process one or more files, or folders containing files, whose icons are dragged onto the droplet icon.
The droplet processes recursively, and will examine the contents of every folder and every sub-folder within those folders, to find and process any appropriate files found.
To use, replace the example processing code in the process_item sub-routine with your code. Save as an application.
*)
(* TO FILTER FOR IMAGE FILES, LOOK FOR QUICKTIME SUPPORTED IMAGE FORMATS *)
property type_list : {"JPEG", "TIFF", "PNGf", "8BPS", "BMPf", "GIFf", "PDF ", "PICT"}
property extension_list : {"jpg", "jpeg", "tif", "tiff", "png", "psd", "bmp", "gif", "jp2", "pdf", "pict", "pct", "sgi", "tga"}
property typeIDs_list : {"public.jpeg", "public.tiff", "public.png", "com.adobe.photoshop-image", "com.microsoft.bmp", "com.compuserve.gif", "public.jpeg-2000", "com.adobe.pdf", "com.apple.pict", "com.sgi.sgi-image", "com.truevision.tga-image"}
global outFile
-- This droplet processes files dropped onto the applet
on open these_items
set outFile to (choose file name with prompt "Output file:" default name "ResolutionReport.txt")
open for access outFile with write permission
-- FILTER THE DRAGGED-ON ITEMS BY CHECKING THEIR PROPERTIES AGAINST THE LISTS ABOVE
repeat with i from 1 to the count of these_items
set this_item to item i of these_items
set the item_info to info for this_item without size
if folder of the item_info is true then
process_folder(this_item)
else
try
set this_extension to the name extension of item_info
on error
set this_extension to ""
end try
try
set this_filetype to the file type of item_info
on error
set this_filetype to ""
end try
try
set this_typeID to the type identifier of item_info
on error
set this_typeID to ""
end try
if (folder of the item_info is false) and (alias of the item_info is false) and ((this_filetype is in the type_list) or (this_extension is in the extension_list) or (this_typeID is in typeIDs_list)) then
-- THE ITEM IS AN IMAGE FILE AND CAN BE PROCESSED
process_item(this_item)
end if
end if
end repeat
close access outFile
end open
-- this sub-routine processes folders
on process_folder(this_folder)
set these_items to list folder this_folder without invisibles
repeat with i from 1 to the count of these_items
set this_item to alias ((this_folder as Unicode text) & (item i of these_items))
set the item_info to info for this_item without size
if folder of the item_info is true then
process_folder(this_item)
else
try
set this_extension to the name extension of item_info
on error
set this_extension to ""
end try
try
set this_filetype to the file type of item_info
on error
set this_filetype to ""
end try
try
set this_typeID to the type identifier of item_info
on error
set this_typeID to ""
end try
if (folder of the item_info is false) and (alias of the item_info is false) and ((this_filetype is in the type_list) or (this_extension is in the extension_list) or (this_typeID is in typeIDs_list)) then
-- THE ITEM IS AN IMAGE FILE AND CAN BE PROCESSED
process_item(this_item)
end if
end if
end repeat
end process_folder
-- this sub-routine processes files
on process_item(this_item)
-- NOTE that the variable this_item is a file reference in alias format
set H_res to 0
set V_res to 0
try
tell application "Image Events"
-- start the Image Events application
launch
-- open the image file
set this_image to open this_item
-- perform action
copy the resolution of this_image to {H_res, V_res}
set outString to ""
if H_res > 0 and V_res > 0 then
set outString to (H_res as string) & " dpi " & (POSIX path of this_item)
else
set outString to "#### ERROR #### " & (POSIX path of this_item)
end if
try
write outString & return to outFile
on error the error_message number the error_number
close access outFile
beep
tell me to activate
display dialog "Error: " & the error_number & ". " & the error_message buttons {"OK"} default button 1
end try
-- purge the open image data
close this_image
end tell
on error error_message number error_number
display alert "PROCESSING ERROR " & error_number message error_message as warning buttons {"Cancel"} cancel button "Cancel"
end try
end process_item
You can try something along the lines of:
on open of theFolder
set outFile to POSIX path of (choose file name with prompt "Output file:" default name "ResolutionReport.txt")
set folderPath to POSIX path of (first item of theFolder)
do shell script "find " & quoted form of folderPath & " -type f -flags nohidden \\! -name \".*\" -exec sips -g dpiHeight {} + | sed 'N;s/\\n//' > " & quoted form of outFile
end open

FileZilla and applescript

I am making an applescript that converts a folder of flv and f4v files to mp4 files and then uploads the to a server via filezilla. How would I use applescript to upload to a server through Filezilla? Here is my code:
--Install handbrakecli into /usr/bin/
--on adding folder items to this_folder after receiving these_items
with timeout of (720 * 60) seconds
tell application "Finder"
--Get all flv and f4v files that have no label color yet, meaning it hasn't been processed
set allFiles to every file of entire contents of ("Macintosh HD:Users:Chase:auto_convert:nope" as alias) whose ((name extension is "flv" or name extension is "f4v") and label index is 0)
--Repeat for all files in above folder
repeat with i from 1 to number of items in allFiles
set currentFile to (item i of allFiles)
try
--label to indicate processing
set label index of currentFile to 3
--Assemble original and new file paths
set origFilepath to quoted form of POSIX path of (currentFile as alias)
set newFilepath to (characters 1 thru -5 of origFilepath as string) & "mp4'"
--Start the conversion
tell application "Terminal"
do shell script "HandBrakeCLI -i " & origFilepath & " -o " & newFilepath
end tell
--Set the label to red because this is the file that has been converted
set label index of currentFile to 6
--Remove the old file
on error errmsg
--Set the label to red to indicate failure
set label index of currentFile to 2
end try
end repeat
set extensionToFind to "mp4"
set topLevelFolder to "Macintosh HD:Users:Chase:auto_convert:nope" as text
set pathCount to count of topLevelFolder
set mp4Files to files of entire contents of folder topLevelFolder whose name extension is extensionToFind
if mp4Files is {} then return
set mp4Folder to "Macintosh HD:Users:Chase:auto_convert:yep"
move mp4Files to mp4Folder
end tell
end timeout
--end adding folder items to
Not a good idea, because Filezilla has no applescript support. I've always been surprised that Cyberduck doesn't either. But see:
http://discussions.apple.com/thread/2588937?start=0&tstart=0
.... on which there are good directions; curl in shell, or (at the end of the page) URL Access Scripting, which is a scripting addition that should be installed on your Mac. URL Access Scripting example:
tell application "URL Access Scripting"
upload filepathtoUpload to "ftp://username:password#domain.com/SOME/PATH/filename.jpg" replacing yes without binhexing
end tell

Applescript copy files to mounted volume; test for file(s) already exists

I am writing a script to allow students to upload their files to a shared folder on teacher's computer in a computer lab (same network). I have a working script that, when executed, will duplicate all files in the folder UPLOAD on the student machine to the folder SUBMISSIONS on the teacher's machine. However, if a file already exists on the teacher machine, the script hangs.
I need to be able to test for the presence of individual files on the teacher machine and either (a) pop a message that says "this file already exists, rename it and upload again" or (b) append something to the file name to differentiate it...a random number or "copy 1" etc.
Ideally I want it to run as a folder action. When a file is added to the "UPLOAD" folder it will automatically be sent to the teacher. But I don't want files to copy over files of the same name...or for the script to hang.
Any thoughts or alterative approaches would be welcome.
Here's my code:
set home_path to path to home folder as string
set work_folder to alias (home_path & "Desktop:" & "Upload")
try
mount volume "afp://[LOGIN INFO].local/Submissions"
set this_folder to result as alias
tell application "Finder"
tell application "Finder"
duplicate every file of work_folder to this_folder
end tell
eject this_folder
end tell
end try
I think that it would help if your try-block had an on-error block to inform you about any errors.
try
# try stuff here
j # this will compile but will throw a runtime error and you can see the error
on error error_message number error_number
display alert "Error: " & error_message & return & return & (error_number as text)
end try
OK. I tried again to write some code. Here is my version.
It does a couple of things differently than the code posted by the original poster.
It copies the files and folders into a new folder on the server with a time-stamp to cope with the problems of whether some of the files already exist on the server.
I changed the wording of the duplicate statement from duplicating every "file" to duplicating every "item" so that folders are duplicated too.
I put in an on-error block in the try-statement to display any errors.
I activate Finder so that you can see the progress window.
I pop up a dialog at the end if there were no errors.
I had a problem that I had to fix:
On the server, I had to enable write permissions for the client or I got a -5000 error.
I think that the following code should work pretty well. It's almost 100% AppleScript. It only uses one call to the shell and that is to get the current date and format it for the time-stamp for new folders created on the server.
# set the path to the "work_folder" where the files are to be uploaded
set home_path to path to home folder as string
set work_folder to alias (home_path & "Desktop:" & "Upload")
# duplicate the files and folders in work_folder to the server
try
# TODO set the name of your server here
set the_volume to mount volume "afp://32-bit.local/Submissions"
set destination_path to the_volume as text
set folder_name to getTimeStamp()
tell application "Finder"
activate
set new_folder to make new folder at alias destination_path with properties {name:folder_name}
duplicate every item of work_folder to new_folder
eject the_volume
display alert "Successfully uploaded the files and folders"
end tell
on error error_message number error_number
if error_number is not equal to -128 then
display alert "Error: " & error_message & return & return & (error_number as text)
end if
end try
# This function returns the current date and time as a time-stamp of the form yyyy-mm-dd-hh-ss
# This function uses a shell script because it's just a lot easier to do than in AppleScript
on getTimeStamp()
set time_stamp to do shell script "date '+%Y-%m-%d-%H-%M-%S'"
return time_stamp
end getTimeStamp
Here's another idea for debugging. You can put in calls to "display dialog" to be able to know where your script is failing:
display dialog "Entering script"
set home_path to path to home folder as string
display dialog "home_path: " & home_path
set work_folder to alias (home_path & "Desktop:" & "Upload")
display dialog "work_folder: " & work_folder as string
try
mount volume "afp://32-bit.local/Submissions"
set this_folder to result as alias
display dialog "this_folder: " & this_folder as string
tell application "Finder"
display dialog "Inside of the first tell application Finder"
tell application "Finder"
display dialog "About to call duplicate"
duplicate every file of work_folder to this_folder
display dialog "Just returned from calling duplicate"
end tell
display dialog "About to call eject"
eject this_folder
display dialog "Just returned from call to eject"
end tell
on error error_message number error_number
display alert "Error:" & error_message & return & return & (error_number as text)
end try
display dialog "Exiting script"
Another debugging technique is to log output to a text file.
Another debugging technique is to purchase the AppleScript debugger:
http://www.latenightsw.com/sd4/index.html
I believe that this debugger costs $200.00 that's too pricey for me, but I've used other debuggers and debuggers are wonderful tools that let you "peek inside" of your script while it's running to see the value of variables and to trace which lines of code are being executed.
This script will copy each file over to the mounted volume. If a file exists with the same name at the destination it will add a number to the end of the copy file name and try that.
Example:if test.doc exists in the folder already then the script will try and copy it with the name test_1.doc and so on..
The original file is never renamed and the older files are never overwritten.
The script is fully commented to explain what it is doing.
** Update2 **
The copy to destination code is now in it's own handler.
The original files are labeled by the finder label index 6 (green) to indicate successful copied.
This will also stop the same original file from being copied twice by using the index colour as a check. If it is labeled index label 7 it will be ignored.
You could if you want move the successful copied files to another folder out of the way using the script. But I have not done this in this script.
set home_path to path to home folder as string
set work_folder to alias (home_path & "Desktop:" & "Upload")
set counter to ""
global counter
--try
set this_folder to mount volume "afp://myMac/UserName/"
this_folder as text
tell application "Finder" to set theFiles to every file of work_folder as alias list #GET ALL FILES OF LOCAL FOLDER AS ALIASES
tell application "Finder" to set theRemoteFiles to (every file of ((this_folder & "Submissions:" as string) as alias)) #GET ALL FILES OF REMOTE FOLDER -- ONLY NEEDED FOR COUNT CHECK LATER
repeat with i from 1 to number of items in theFiles #PROCESS EACH LOCAL FILE
set this_item to item i of theFiles #GET A LOCAL FILE
tell application "Finder" to set LabelIndex to label index of this_item
if LabelIndex is not 6 then
tell application "Finder" to set this_name to displayed name of this_item #GET ITS DISPLAYED NAME
tell application "Finder" to set this_extension to name extension of this_item #GET ITS EXTENSION NAME i.E "txt"
set realName to (do shell script "echo " & quoted form of this_name & "| awk -F '" & quoted form of this_extension & "' '{print $1}'") #GET ITS NAME WITHOUT EXTENSION NAME
set counter to 1 # SET A NUMBER TO ADD TO THE FILE NAME IF THE FILE NAME EXIST ALREADY IN THE REMOTE FOLDER
my checkName(this_name, realName, this_item, this_extension, theRemoteFiles, this_folder) # CALL TO HANDLER THAT WILL DO THE CHECKING AND COPYING
end if
end repeat
tell application "Finder" to eject this_folder
# THE CALL TO THE HANDLER INCLUDES VARIABLES THAT ARE NOT GLOBAL OR PROPERTIES BUT NEED TO BE PASSED ON TO IT I.E(this_name, realName, this_item, this_extension, theRemoteFiles, this_folder)
on checkName(this_name, realName, this_item, this_extension, theRemoteFiles, this_folder)
# (1) IF THE NUMBER OF theRemoteFiles IS GREATER THAN 0 THEN FILES EXIST IN THE REMOTE FOLDER AND MAY CONTAIN FILES WITH THE SAME NAMES AS THE LOCAL ONES. PROCESS..
# (2) IF THE NUMBER OF theRemoteFiles IS NOT GREATER THAN 0.THEN FILES DO NOT EXIST IN THE REMOTE FOLDER AND THE LOCAL ONES CAN JUST BE COPIED OVER.
if (count of theRemoteFiles) is greater than 0 then # (1)
try
my copyOver(this_item, this_folder, this_name)
on error errMssg #WE USE not overwritten ERROR TO TRIGGER THE RENAME THE DESTINATION FILE NAME TO INCLUDE A NEW NUMBER.
--tell application "Finder" to set label index of this_item to 6
if errMssg contains "not overwritten" then
set this_name to (realName & counter & "." & this_extension)
set counter to counter + 1 #WE SETUP THE FILE NAME NUMBER FOR THE POSSIBLE NEXT RUN
# RUN THE HANDLER AGAIN WITH THE CHANED DETAILS
my checkName(this_name, realName, this_item, this_extension, theRemoteFiles, this_folder)
end if
end try
else # (2)
my copyOver(this_item, this_folder, this_name)
end if
end checkName
on copyOver(this_item, this_folder, this_name)
# THE -n OPTION IN THE SHELL COMMAND TELLS CP NOT TO OVERWRITE EXISTING FILES. AN ERROR OCCURE IF THE FILE EXISTS.
# THE -p OPTION IN THE SHELL COMMAND TELLS CP TO PRESERVE THE FOLLOWING ATTRIBUTES OF EACH SOURCE FILE IN THE COPY:
# modification time, access time, file flags, file mode,
#user ID, and group ID, as allowed by permissions. Access Control
#Lists (ACLs) and Extended Attributes (EAs), including resource
#forks, will also be preserved.
# THE -v OPTION IN THE SHELL COMMAND TELLS CP TO USE VERBOS MODE. WHICH GIVES US A BETTER CLUE OF THE ERROR
set theResult to (do shell script "cp -npv " & quoted form of (POSIX path of this_item) & space & quoted form of (POSIX path of (this_folder & "Submissions:" as string) & this_name))
if theResult contains "->" then
tell application "Finder" to set label index of this_item to 6
else
tell application "Finder" to set label index of this_item to 7
end if
end copyOver

Automator/AppleScript to find same file name with different extension in same directory

I'd like to create an automator action to help manage DNG/XMP files. I'd like to be able to drag a DNG (or several) onto the action which will send the DNG and the matching XMP file to the trash. The files have the same name except for the extension, they are in the same directory. For example, IMGP1361.DNG and IMGP1361.xmp
This would be a simple task for a shell script, but is there an Automator way to do it (to learn more about Automator)? Is there a way to get at the file name of the input finder item, change it in a variable and use that as input to another action?
Thanks.
This script for Automator will delete all of the files that share the same prefix and whose name extension is listed in the grep command. You may add additional extensions as well. (xmp|DNG|pdf|xls)
on run {input, parameters}
try
repeat with anItem in input
tell (info for anItem) to set {theName, theExt} to {name, name extension}
set shortName to text 1 thru ((get offset of "." & theExt in theName) - 1) of theName
tell application "Finder"
set parentFolder to parent of anItem as alias
set matchList to every paragraph of (do shell script "ls " & POSIX path of parentFolder & " | grep -E '" & shortName & ".(xmp|DNG)'")
delete (every file of parentFolder whose name is in matchList)
end tell
end repeat
end try
end run
OK, got it. You can use the AppleScript given below inside an Automator workflow like this:
For every selected file in the Finder, if its extension is in ext_list, it will be moved to the Trash, and so will all other files of the same name in the same folder whose extension is one of those in also_these_extensions.
It can be useful, e.g. also for cleaning a folder with auxiliary LaTeX files: just put "tex" into ext_list and all the other extensions (such as "aux", "dvi", "log") into also_these_extensions.
The selected files don't need to be inside the same folder; you can also select several items in a Spotlight search results window.
on run {input, parameters}
-- for every item having one of these extensions:
set ext_list to {"dng"}
-- also process items with same name but these extensions:
set other_ext_list to {"xmp"}
tell application "Finder"
set the_delete_list to {}
set delete_list to a reference to the_delete_list
-- populate list of items to delete
repeat with the_item in input
set the_item to (the_item as alias)
if name extension of the_item is in ext_list then
copy the_item to the end of delete_list
set parent_folder to (container of the_item) as alias as text
set item_name to text 1 thru ((length of (the_item's name as text)) - (length of (the_item's name extension as text))) of (the_item's name as text)
repeat with ext in other_ext_list
try
copy ((parent_folder & item_name & ext) as alias) to the end of delete_list
end try
end repeat
end if
end repeat
-- delete the items, show info dialog
move the_delete_list to the trash
display dialog "Moved " & (length of the_delete_list) & " files to the Trash." buttons {"OK"}
end tell
end run

Automator/Applescript File Sorting and Moving

I was wondering if there was a way in Automator to use Applescript code to get the extension of a file, and if it equals a specific extension (e.g. .pdf or .rtf) move to a specific folder for that extension (e.g if (extension == pdf) { move to folder "~/PDF Files" } else if (extension == rtf) { move to folder "~/Rich Text Files" })
Here's an applescript. Since your request was simple I just wrote it for you. Note how I get the file extension with the subroutine "getNameAndExtension(F)". Normally you can get the file extension from the Finder (called name extension) but I've found that the Finder is not always reliable so I always use that subroutine. That subroutine has always been reliable.
set homeFolder to path to home folder as text
set rtfFolderName to "Rich Text Files"
set pdfFolderName to "PDF Files"
-- choose the files
set theFiles to choose file with prompt "Choose RTF or PDF files to move into your home folder" with multiple selections allowed
-- make sure the folders exist
tell application "Finder"
if not (exists folder (homeFolder & rtfFolderName)) then
make new folder at folder homeFolder with properties {name:rtfFolderName}
end if
if not (exists folder (homeFolder & pdfFolderName)) then
make new folder at folder homeFolder with properties {name:pdfFolderName}
end if
end tell
-- move the files
repeat with aFile in theFiles
set fileExtension to item 2 of getNameAndExtension(aFile)
if fileExtension is "rtf" then
tell application "Finder"
move aFile to folder (homeFolder & rtfFolderName)
end tell
else if fileExtension is "pdf" then
tell application "Finder"
move aFile to folder (homeFolder & pdfFolderName)
end tell
end if
end repeat
(*=============== SUBROUTINES ===============*)
on getNameAndExtension(F)
set F to F as Unicode text
set {name:Nm, name extension:Ex} to info for file F without size
if Ex is missing value then set Ex to ""
if Ex is not "" then
set Nm to text 1 thru ((count Nm) - (count Ex) - 1) of Nm
end if
return {Nm, Ex}
end getNameAndExtension
I'm not at my Apple right now, so I can't play around with Automator and figure it out. But if you could do this by switching finder to list view, sort by type, and then select blocks of files of the same type and drag them into the right folder.

Resources