Automator/Applescript File Sorting and Moving - applescript

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.

Related

AppleScript : How to get files in folder without hidden files?

I actually have two questions.
How to exclude hidden files like .DS_STORE, Icon when I try to get files in folder ?
I've tried "without invisibles" but it seems not working.
How to set my var the_new_folder as an existing folder if already exists ?
Thanks for answers.
My code:
--
-- Get all files in a selected folder
-- For each file, create a folder with the same name and put the file in
--
tell application "Finder"
set the_path to choose folder with prompt "Choose your folder..."
my file_to_folder(the_path)
end tell
on file_to_folder(the_folder)
tell application "Finder"
-- HELP NEEDED HERE
-- HOW TO EXCLUDE HIDDEN FILES (Like Icon, .DS_STORE, etc)
set the_files to files of the_folder
repeat with the_file in the_files
-- Exclude folder in selection
if kind of the_file is not "Folder" then
set the_path to container of the_file
set the_file_ext to name extension of the_file
-- Remove extension of the file name
set the_file_name to name of the_file as string
set the_file_name to text 1 thru ((offset of the_file_ext in (the_file_name)) - 2) of the_file_name
-- Make the new folder with the file name
try
set the_new_folder to make new folder at the_path with properties {name:the_file_name}
on error
-- HELP NEEDED HERE
-- HOW TO SET the_new_folder AS THE EXISTING FOLDER
end try
-- Move the file in the new folder
move the_file to the_new_folder
end if
end repeat
end tell
end file_to_folder
tell application "Finder"
(display dialog ("It's done!") buttons {"Perfect!"})
end tell
Using the System Events context instead of Finder:
bypasses the problem with the AppleShowAllFiles preference[1]
is much faster in general.
Using the visible property of file / folder objects in the System Events context allows you to predictably determine either all items, including hidden ones (by default), or only the visible ones (with whose visible is true):
# Sample input path.
set the_path to POSIX path of (path to home folder)
tell application "System Events"
set allVisibleFiles to files of folder the_path whose visible is true
end tell
Simply omit whose visible is true to include hidden files too.
The code for either referencing a preexisting folder or creating it on demand is essentially the same as in the Finder context:
# Sample input path.
set the_path to POSIX path of (path to home folder)
# Sample subfolder name
set the_subfolder_name to "subfolder"
tell application "System Events"
if folder (the_path & the_subfolder_name) exists then
set subfolder to folder (the_path & the_subfolder_name)
else
set subfolder to make new folder at folder the_path ¬
with properties {name: the_subfolder_name}
end if
end tell
[1] In order to predictably exclude hidden items, a Finder-based solution is not only cumbersome but has massive side effects:
You need to determine the current state of the the AppleShowAllFiles preference (defaults read com.apple.Finder AppleShowAllFiles),
then turn it off.
then kill Finder to make the change take effect (it restarts automatically) - this will be visually disruptive
then, after your code has run, restore it to its previous value.
then kill Finder again so that the restored value takes effect again.
I believe that your first question is not a problem. Your code works fine for me.
As for the second issue, the simplest method is to use the text representation of the_path, and simply build the new folder, and see if it already exists:
set the_path_Text to (the_path as text)
set try_Path to the_path_Text & the_file_name
if (folder try_Path) exists then
set the_new_folder to (folder try_Path)
else
set the_new_folder to make new folder at the_path with properties {name:the_file_name}
end if
If you are truly having difficulty with the first code section, please post a new question with more details, such as a copy of the Result section of the Script.
Thank you to all of you ! #mklement0 #craig-smith
You will find below the corrected code with your help!
If I share this code, you want to be cited for thanks?
--
-- Get all files in a selected folder
-- For each file, create a folder with the same name and put the file in
--
-- Get user folder
set the_path to choose folder with prompt "Choose your folder..."
my file_to_folder(the_path)
on file_to_folder(the_folder)
tell application "System Events"
-- Get all files without hidden
set the_files to files of the_folder whose visible is true
repeat with the_file in the_files
-- Remove extension of the file name
set the_file_ext to name extension of the_file
set the_file_name to name of the_file as string
set the_file_name to text 1 thru ((offset of the_file_ext in (the_file_name)) - 2) of the_file_name
-- Make a new folder or get the existing
set the_path to POSIX path of the_folder
if folder (the_path & the_file_name) exists then
set the_new_folder to folder (the_path & the_file_name)
else
set the_new_folder to make new folder at folder the_path with properties {name:the_file_name}
end if
-- Move the file to the new folder
move the_file to the_new_folder
end repeat
end tell
end file_to_folder
-- Ending dialog
display dialog ("It's done!") buttons {"Perfect!"}

Create new folder from files name and move files

(This is a new edit from a previous question of mine which achieved -3 votes. Hope this new one has a better qualification)
I need to create an Automator service to organize a high amount of files into folders. I work with illustrator and from each .ai file I create 3 more formats: [name.pdf], [name BAJA.jpg] and [name.jpg], thats 4 files in total
My problem is that during the week I repeat this process to more than 90 different .ai files. So 90 files * 4 is 360 independent files all into the some project folder.
I want to grab all 4 related files into one folder, and set the folder name as the same as the .ai file.
Since all the file names are identical (except one), I thought of telling the finder to grab all the files with the same name, copy the name, create a folder and put this files inside, but I have a file name variant [name LOW.jpg] Maybe I can tell the script to strip that work as an exception.
That way I will all 4 the files unified into one folder.
Thank you in advance
Update: This problem was originally posted back in 2013, now I have a solution. People help me assembled this script to fit my needs.
I added this as a service and assigned a keyboard shurtcut on MacOs.
This is the code:
on run {input, parameters} -- create folders from file names and move
set output to {} -- this will be a list of the moved files
repeat with anItem in the input -- step through each item in the input
set {theContainer, theName, theExtension} to (getTheNames from anItem)
try
# check for a suffix and strip it off for the folder name
if theName ends with " BAJA" then
set destination to (makeNewFolder for (text 1 thru -6 of theName) at theContainer)
else
set destination to (makeNewFolder for theName at theContainer)
end if
tell application "Finder"
move anItem to destination
set the end of the output to the result as alias -- success
end tell
on error errorMessage -- duplicate name, permissions, etc
log errorMessage
# handle errors if desired - just skip for now
end try
end repeat
return the output -- pass on the results to following actions
end run
to getTheNames from someItem -- get a container, name, and extension from a file item
tell application "System Events" to tell disk item (someItem as text)
set theContainer to the path of the container
set {theName, theExtension} to {name, name extension}
end tell
if theExtension is not "" then
set theName to text 1 thru -((count theExtension) + 2) of theName -- just the name part
set theExtension to "." & theExtension
end if
return {theContainer, theName, theExtension}
end getTheNames
to makeNewFolder for theChild at theParent -- make a new child folder at the parent location if it doesn't already exist
set theParent to theParent as text
if theParent begins with "/" then set theParent to theParent as POSIX file as text
try
return (theParent & theChild) as alias
on error errorMessage -- no folder
log errorMessage
tell application "Finder" to make new folder at theParent with properties {name:theChild}
return the result as alias
end try
end makeNewFolder
Hope this helps.
It's a pity you get downvoted as I, personally, enjoy answering these sorts of questions, as it helps me practise and improve my own skills.
Thanks for posting your solution. I think it's a great gesture and others will find it useful.
This script is a bit shorter than and uses "System Events" instead of "Finder", so will be quicker for large numbers of files:
set IllustratorOutputFolder to "/Users/CK/Desktop/example"
tell application "System Events" to ¬
set ai_files to every file in folder IllustratorOutputFolder ¬
whose name extension is "ai"
set Output to {}
repeat with ai_file in ai_files
set AppleScript's text item delimiters to "."
get name of ai_file
get text items of result
set basename to reverse of rest of reverse of result as text
tell application "System Events"
get (every file in folder IllustratorOutputFolder ¬
whose name begins with basename)
move result to (make new folder ¬
in folder IllustratorOutputFolder ¬
with properties {name:basename})
end tell
set end of Output to result
end repeat
return Output -- list of lists of moved files
Just an alternative way of doing things. Not that it's better or worse, but just a different solution.
You could also save this as script.sh (in TextEdit in plain text mode) and run it with bash script.sh in Terminal:
cd ~/Target\ Folder/
for f in *.ai *.pdf *.jpg; do
dir=${f%.*}
dir=${dir% LOW}
mkdir -p "$dir"
mv "$f" "$dir"
done

how to use applescript to move files to new folder by extension, keeping subfolder name

Here's what I'm trying to do.
I've got a file structure that contains photos in both JPG and RAW formats. It's a folder called "Photos" with subfolders by date. I'd like to copy just the RAW photos to a new folder, "Photos RAW", but keep the structure by date taken/created.
I can copy just the files using automator or applescript a directory to a new one, but how do I walk the directory tree using applescript so I cover all the subfolders?
Try this. You'll see I used "entire contents" to get the files in the subfolders too.
set extensionToFind to "raw"
set topLevelFolder to (choose folder) as text
set pathCount to count of topLevelFolder
tell application "Finder"
-- get the files
set rawFiles to files of entire contents of folder topLevelFolder whose name extension is extensionToFind
if rawFiles is {} then return
-- setup the folder where the files will be moved
set rawFolder to ((container of folder topLevelFolder) as text) & "Photos_Raw:"
do shell script "mkdir -p " & quoted form of POSIX path of rawFolder
repeat with aFile in rawFiles
set aFileContainer to (container of aFile) as text
if topLevelFolder is equal to aFileContainer then
-- here the file is at the top level folder
set newPath to rawFolder
else
-- here we calculate the new path and make sure the folder structure is in place
set thisFile to aFile as text
set subFolderPath to text (pathCount + 1) thru -((count of (get name of aFile)) + 1) of thisFile
set newPath to rawFolder & subFolderPath
do shell script "mkdir -p " & quoted form of POSIX path of newPath
end if
move aFile to folder newPath
end repeat
end tell

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

Applescript: make new folder structure if it doesn't exist

I've been searching through message boards trying to figure out how to execute this script. Essentially the goal is to be able to run this script while inside a folder and if certain folders do not exist, these folders would then be created. If they do already exist, nothing happens. Here's what I've cobbled together so far:
property archivesFolder : "Archives"
property imagesFolder : "Images"
property proofreadFolder : "Proofreading"
property proofFolder : "Proofs"
property sourceFolder : "Source"
try
tell application "Finder" to set theLocation to (folder of the front window as alias)
end try
tell application "Finder"
if (exists folder archivesFolder) then
(* do nothing *)
else
make new folder at theLocation with properties {name:archivesFolder}
end if
if (exists folder imagesFolder) then
(* do nothing *)
else
make new folder at theLocation with properties {name:imagesFolder}
end if
if (exists folder proofreadFolder) then
(* do nothing *)
else
make new folder at theLocation with properties {name:proofreadFolder}
end if
if (exists folder proofFolder) then
(* do nothing *)
else
make new folder at theLocation with properties {name:proofFolder}
end if
if (exists folder sourceFolder) then
(* do nothing *)
else
make new folder at theLocation with properties {name:sourceFolder}
end if
end tell
What am I doing wrong ? (forgive my n00b code formatting, at work and can't figure out how to create code blocks) Also, is it possible to this not just on the front window, but on a folder that is just selected? Any help given would be awesome.
I suggest two options (to run the script):
Option 1: Take that code (assuming it does what you plan), and save it as an application (with Script Editor).
Then, just drag that application to your window toolbar (you need to have the toolbar visible). To do that, hold the command key while dragging.
Option 2: Use Butler: http://manytricks.com/butler/
(there is a free version, I don't know your OSX version).
It allows you to define system-wide shortcut keys for applescript scripts.
Create a smart item (applescript); paste the code there, and in the name of the script add the shortcut keys: example: create folder here ⇧⌥⌘N
EDIT:
According to your comment, I understand your problem and I can tell you that you were missing the path (the current folder, in your case theLocation)
So, in every case of if (exists folder archivesFolder) then you need to add the of theLocation like this: if not (exists folder archivesFolder of theLocation) then
Finally, knowing that you won't do any thing if the folder exists, just test the false case.
I tested this code and am posting it here:
property archivesFolder : "Archives"
property imagesFolder : "Images"
property proofreadFolder : "Proofreading"
property proofFolder : "Proofs"
property sourceFolder : "Source"
try
tell application "Finder" to set theLocation to (folder of the front window as alias)
end try
tell application "Finder"
if not (exists folder archivesFolder of theLocation) then
make new folder at theLocation with properties {name:archivesFolder}
end if
if not (exists folder imagesFolder of theLocation) then
make new folder at theLocation with properties {name:imagesFolder}
end if
if not (exists folder proofreadFolder of theLocation) then
make new folder at theLocation with properties {name:proofreadFolder}
end if
if not (exists folder proofFolder of theLocation) then
make new folder at theLocation with properties {name:proofFolder}
end if
if not (exists folder sourceFolder of theLocation) then
make new folder at theLocation with properties {name:sourceFolder}
end if
end tell
You can also use a shell script with mkdir, since the option to create intermediate folders won't error if the folder already exists.
# define a list of folders - items will need to be quoted if they contain spaces, etc.
property theFolders : {"Archives", "Images", "ProofReading", "Proofs", "Source"} -- can also nest, e.g. "Inside/One"
try
tell application "Finder" to set targetFolder to (target of the front window) as alias
on error -- no window
set targetFolder to (choose folder)
end try
# build a parameter string from the folder list
set {tempTID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, space}
set {theFolders, AppleScript's text item delimiters} to {theFolders as text, tempTID}
do shell script "cd " & quoted form of POSIX path of targetFolder & "; mkdir -p " & theFolders
Try this:
tell application "Finder"
set theLocation to (target of front window) as string
set folderNames to {"archivesFolder", "imagesFolder", "proofreadFolder", "proofFolder", "sourceFolder"}
repeat with theFolder in folderNames
try
make new folder at theLocation with properties {name:"" & theFolder & ""}
end try
end repeat
end tell
This is a script I did to sort a bunch of medical files into subfolders based on the date of service (explaining the "text 5 thru 14" in the script; the files are named according to a pattern so the script can extract the date of service from the filename). Rather than check if the folder already exists, I just put the make folder instruction in a try block; if the folder already exists, the 'try' fails, but the script continues under the assumption that the folder already exists. Using the 'text' item instead of 'character' returns the extracted string as a single string and not as an array of characters that have to be converted back into a string.
tell application "Finder"
set theDirectory to "Internal Disk:Users:steven:Documents:Vondalee:Medical"
set theFiles to every file in folder theDirectory whose name extension is "pdf"
repeat with eachFile in theFiles
set theFileName to the name of eachFile
set theFolder to text 5 thru 14 of theFileName
try
make new folder at theDirectory with properties {name:theFolder}
end try
move eachFile to folder theFolder of folder theDirectory
end repeat
end tell

Resources