Create new folder from files name and move files - applescript

(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

Related

"Tag and move" Applescript no longer works (High Sierra)

Firstly, let me stress that I have almost no Applescript experience. I'm an Oracle developer by trade, so please assume my knowledge is ZERO so I'd be grateful if you could really dumb down your response.
I wrote this script a year or so ago and it has suddenly stopped working. I'm guessing that a macOS upgrade (on High Sierra) no longer tolerates my probably poorly written script.
on run {input, parameters}
repeat with theFile in input
set FileName to theFile as text
tell application "Finder"
if FileName ends with "-xs.jpg" then
--label value, 0 is no label, 1 Orange, 2 Red, 6 Geen
set the label index of file FileName to 6
move FileName to folder "Macintosh HD:Users:Karla:Pictures:FTP:basket-[xs]:" with replacing
else if FileName ends with "-sm.jpg" then
set the label index of file FileName to 1
move FileName to folder "Macintosh HD:Users:Karla:Pictures:FTP:thumbnails-[sm]:" with replacing
else if FileName ends with "-lg.jpg" then
set the label index of file FileName to 2
move FileName to folder "Macintosh HD:Users:Karla:Pictures:FTP:main-[lg]:" with replacing
else if FileName ends with "-xlg.jpg" then
set the label index of file FileName to 5
move FileName to folder "Macintosh HD:Users:Karla:Pictures:FTP:large-[xlg]:" with replacing
end if
end tell
end repeat
return input
end run
The error I get is "The action "Run AppleScript" encountered an error: "Finder got an error: Can't set file "Macintosh HD:Users:Karla:Pictures:1-IMAGES-TO-DO:image1-lg.jpg" to 2."
If I comment out the tagging and try to just do the move, I get "The action "Run AppleScript" encountered an error: "Finder got an error: Can't get folder "Mackintosh HD:Users:Karla:Pictures:FTP:main-[lg]:"."
Edit:
I have also tried:
on run {input, parameters}
repeat with the_input_file in input
set FileName to POSIX file (the_input_file as alias)
end repeat
return input
end run
but get the error The action "Run AppleScript" encountered the error: "Can't get POSIX file (alias "Macintosh HD:Users:Karla:Pictures:file.jpg")."
Edit again:
So this is where I am. I've created a droplet as follows:
on open theDroppedItems
set lg_folder to POSIX path of "Macintosh HD:Users:Karla:Pictures:test1:"
repeat with current_item_cnt from 1 to count of theDroppedItems
-- load the next file in the_file
set the_current_file to item current_item_cnt of theDroppedItems
move file the_current_file to lg_folder
end repeat
end open
And I still get a -1728 error onthe file. "Can’t get file (alias \"Macintosh HD:Users:Karla:Pictures:test1:test-lg.jpg\")." number -1728 from file (alias "Macintosh HD:Users:Karla:Pictures:test1:test-lg.jpg")
I've spent 2 days on a script that used to work and now inexplicably does not in amongst trying to do my real job. This is supposed to make my life easier.
Try using this code for your droplet...
property folderXS : "Macintosh HD:Users:Karla:Pictures:FTP:basket-[xs]"
property folderSM : "Macintosh HD:Users:Karla:Pictures:FTP:thumbnails-[sm]"
property folderLG : "Macintosh HD:Users:Karla:Pictures:FTP:main-[lg]"
property folderXL : "Macintosh HD:Users:Karla:Pictures:FTP:large-[xlg]"
on run
-- Executed when the script is launched
set theFiles to choose file with prompt ¬
"Choose Files" multiple selections allowed true ¬
without showing package contents
repeat with theFile in theFiles
set FileName to theFile as text
tell application "Finder"
if FileName ends with "-xs.jpg" then
--label value, 0 is no label, 1 Orange, 2 Red, 6 Green
set the label index of file FileName to 6
move FileName to folder folderXS with replacing
else if FileName ends with "-sm.jpg" then
set the label index of file FileName to 1
move FileName to folder folderSM with replacing
else if FileName ends with "-lg.jpg" then
set the label index of file FileName to 2
move FileName to folder folderLG with replacing
else if FileName ends with "-xlg.jpg" then
set the label index of file FileName to 5
move FileName to folder folderXL with replacing
end if
end tell
end repeat
return theFiles
end run
on open theDroppedItems
-- Executed when files are dropped on the script
set lg_folder to "Macintosh HD:Users:Karla:Pictures:test1"
repeat with current_item_cnt from 1 to count of theDroppedItems
set the_current_file to item current_item_cnt of theDroppedItems
tell application "Finder"
move file the_current_file to lg_folder
end tell
end repeat
end open
If anybody comes here as I did, looking for an answer, I can give you an inelegant, hacky way to at least get this working. I had variable this_item which contained an HFS file which I wanted to move into todaysFolder.
Part of the problem is Finder doesn't always know what to do with POSIX paths involving variables, and sometimes you need to use the "my" keyword first. Other time, you need to leave it out. I couldn't figure out the logic.
The following ridiculous code block does it reliably and seems to catch every strange, inscrutable exception.
try
move my (POSIX file (POSIX path of this_item)) to folder (todaysFolder) of disk "Hard Drive" with replacing
on error
try
move (POSIX file (POSIX path of this_item)) to folder (todaysFolder) of disk "Hard Drive" with replacing
on error
try
move (file (POSIX path of this_item)) to folder (todaysFolder) of disk "Hard Drive" with replacing
on error
move (file (this_item)) to folder (todaysFolder) of disk "Hard Drive" with replacing
end try
end try
end try

Applescript / Finder select specific items in a folder including those in disclosed subfolders by file name or file path list

Here's our situation:
We have a list of file names and/or full file paths (we can generate either)
The files in our list are all contained under one folder, but scattered across multiple sub-folders. (There are hundreds of items in our select list from thousands of possible files. Selecting manually isn't an option)
We've got the root folder open in list view and all sub-folders, sub-sub etc disclosure-opened (btw thanks to http://hints.macworld.com/article.php?story=20030218164922494 for the shortcut "command, option, control and shift when pressing the right arrow")
With all files visible under one window open we want to automatically select all the items in our file list so that they can then be dragged at once to an application.
I do not believe that with basic AppleScript one can programmatically select multiple items in Finder which span throughout different folders and subfolders within a given folder in one window. Maybe with Cocoa-AppleScript, don't know, however if Avid can open files from file aliases, then the following example AppleScript code is a viable option.
The example AppleScript code makes the following assumptions:
There is a plain text file containing the fully qualified POSIX pathnames of the target files to be processed with Avid and the name of the file is: List of Files to Process with Avid.txt
The name of the folder containing the aliases is: Aliases of Files to Process with Avid
The Desktop is used as the location in the filesystem that the aforementioned file and folder exists, to be processed by Avid.
Obviously these settings can be changed as needed/wanted, see the comments in the code.
Example AppleScript code:
-- # Set the value of the following three property variables:
-- #
-- # The value of 'thisLocation' is an colon-delimited path string, e.g. 'path to desktop as string' returns: "Macintosh HD:Users:me:Desktop:"
-- # NOTE: When not using 'path to (folder)' where 'folder' is a 'folder constant' , the special folder for which to return the path, the value should be in the form of an colon-delimited path string.
-- # See: https://developer.apple.com/library/content/documentation/AppleScript/Conceptual/AppleScriptLangGuide/reference/ASLR_cmds.html#//apple_ref/doc/uid/TP40000983-CH216-SW19
-- #
-- # The value of 'theListFilename' is the name of the plain text file containing the fully quilified pathnames of the target files to be opened in Avid.
-- # The value of 'theFolderName' is the name of the temporary folder the temporary aliases will be created in. This folder gets created new each run with new aliases.
-- #
-- # NOTE: For ease of use, as each run is presumed to be temporary to get that job run done, the location of the 'theListFilename' and 'theFolderName' are both in 'thisLocation'.
property thisLocation : (path to desktop as string)
property theListFilename : "List of Files to Process with Avid.txt"
property theFolderName : "Aliases of Files to Process with Avid"
-- # The remaining code is tokenized and should not need to be modified.
tell application "Finder"
if (exists thisLocation & theListFilename) then
tell current application to set theList to read alias (thisLocation & theListFilename)
else
display dialog "The file, \"" & theListFilename & "\", was not found at the expected location." buttons {"OK"} ¬
default button 1 with title "Missing File" with icon 0
return
end if
set theFolderPathname to thisLocation & theFolderName
if not (exists theFolderPathname) then
make new folder at thisLocation with properties {name:theFolderName}
else
move theFolderPathname to trash
make new folder at thisLocation with properties {name:theFolderName}
end if
repeat with i from 1 to length of theList
try
make new alias file at theFolderPathname to POSIX file (paragraph i of theList)
end try
end repeat
reveal theFolderPathname
activate
-- delay 1 -- # In necessary, uncomment and adjust value as appropriate.
select every item of alias theFolderPathname
end tell
In Script Editor, save this script and an application, e.g. Select Files to Process with Avid, and then run as needed after replacing the e.g. List of Files to Process with Avid.txt with the current set of target files to be processed with Avid.
The script does the following:
Checks to see the file e.g. List of Files to Process with Avid.txt exists and if not displays error message and exits.
Checks to see if the folder e.g. Aliases of Files to Process with Avid exist and if not creates it, and if it exists, moves it to the Trash and creates it anew, for the new run of target files to be processed.
Creates an alias of each file listed, as a fully qualified POSIX pathname, in the file e.g.: List of Files to Process with Avid.txt
Opens the folder, e.g. Select Files to Process with Avid, in Finder and selects the aliases.
You are now ready to drag and drop the selected aliases to Avid.
Note: This script assumes the fully qualified POSIX pathnames of the target files to be processes with Avid do not contain linefeeds, carriage returns and or null characters in their pathnames.
This works using the latest version of Sierra.
I was not able to figure out a way to selectively select files in folders with subfolders with subfolders etc. The only solution I was able to come up with was to create folder called “Aliases” and have AppleScript create alias files to all of the ”selected files” and store all of the aliases in the aliases folder. From there you can drag all of the files and drop them into your application as you desired
If you have a plain text file containing POSIX path filenames, each on a separate line like the example in this next image, this version will load the pathnames from the text file directly into the script. Just save this script as an application. You can drag text files directly onto the icon of the app because the code is set up to be a droplet
global theFile
property theInfo : missing value
property theName : missing value
property theList : {}
property theList2 : {}
property aliasFolder : (path to desktop as text) & "Aliases"
on open theFiles
set theInfo to info for theFiles
set theName to POSIX path of theFiles
getLinesofFileAsList(theName)
tell application "Finder"
if not (exists of alias aliasFolder) then
make new folder at (path to desktop as text) with properties {name:"Aliases"}
end if
delete every item of alias aliasFolder
end tell
repeat with i from 1 to count of theList
try
set theResult to POSIX file (item i of theList) as text
set end of theList2 to theResult
tell application "Finder"
set theAliases to make new alias file at aliasFolder to theResult
end tell
end try
end repeat
delay 0.5
tell application "Finder"
activate
delay 0.5
set hmmm to reveal aliasFolder
delay 0.5
set hmmm to select every item of alias aliasFolder
activate hmmm
end tell
end open
on getLinesofFileAsList(theName)
set theFile to theName
set theFile to POSIX path of theName
set theList to read POSIX file theFile as text
set saveTID to AppleScript's text item delimiters
set AppleScript's text item delimiters to linefeed
set theList to paragraphs of theList
if last item of theList is "" then
set theList to reverse of rest of reverse of theList
end if
set AppleScript's text item delimiters to saveTID
end getLinesofFileAsList
--on run
-- -- Handle the case where the script is launched without any dropped files
--end run

Applescript - move files to folder which name begins with first 7 characters of filename

I've got 2 folders
the first folder contains all the files which I'd like to move to a subfolder of the second folder. I'd like to this based on the first 7 characters of both the file & folder names.
So if the first 7 characters of the subfolder in FOLDER 2 matches the first 7 characters of the file in FOLDER 1. The file get's moved into the subfolder of FOLDER 2
Right now I've got an Applescript which works, but it's terribly slow.
Here's the script so far:
set mgFileList to ""
set mgDestFolder to ""
set mgFilesFolder to (choose folder with prompt "Where are the files stored which you would like to move to the destination?")
set mgDestFolder to (choose folder with prompt "Where is the destination folder?")
set folderList to contents of mgDestFolder
tell application "Finder" to set fileList to files of mgFilesFolder
repeat with aFile in fileList
set prefix to getPrefix(name of aFile)
tell application "Finder"
try
set destinationFolder to (1st folder of mgDestFolder whose name begins with prefix)
move aFile to destinationFolder
end try
end tell
end repeat
on getPrefix(aName)
set prefix to text 1 thru 7 of aName
return prefix
end getPrefix
I've only recently got into Applescripting. Can this be done more efficiently within Applescript? I've searched around for a solution which works with a shell script (which I think will probably be a lot faster), but haven't been able to get any of them working.
I'm working on OSX Mountain Lion 10.8.4
--
edit
I see that I've uploaded the wrong version of the script I've managed to put together so far. Above is the script that is working, but it's really slow. Probably because it doesn't use any shell script.
---------------update-------------------
Here is the final script that is working pretty fast right now:
set mgFilesFolder to choose folder with prompt "Where are the files stored which you would like to move to the destination?"
set mgDestFolder to choose folder with prompt "Where is the destination folder?"
tell application "System Events"
set fileList to files of mgFilesFolder whose name does not start with "."
repeat with aFile in fileList
set prefix to my getPrefix(name of aFile)
try
set destinationFolder to (1st folder of mgDestFolder whose name begins with prefix)
move aFile to POSIX path of destinationFolder
end try
end repeat
end tell
on getPrefix(aName)
try
set prefix to text 1 thru 7 of aName
return prefix
on error
return aName
end try
end getPrefix
The Finder is generally a slow program because it does a lot of things on your computer. Therefore you should avoid using it if possible. In your case these tasks can be done using System Events. Try this, maybe it will be faster. Note that you had a couple mistakes in your code which are fixed in this code.
set mgFilesFolder to choose folder with prompt "Where are the files stored which you would like to move to the destination?"
set mgDestFolder to choose folder with prompt "Where is the destination folder?"
tell application "System Events"
set fileList to files of mgFilesFolder whose name does not start with "."
repeat with aFile in fileList
set prefix to my getPrefix(name of aFile)
try
set destinationFolder to (1st folder of mgDestFolder whose name begins with prefix)
move aFile to POSIX path of destinationFolder
end try
end repeat
end tell
on getPrefix(aName)
try
set prefix to text 1 thru 7 of aName
return prefix
on error
return aName
end try
end getPrefix
Not sure how many files you're working with, but I tested this with 10 folders and ~100 files, and it took less than 4 seconds to run. Working with strings is much faster than working with files, so the script gets the files/folders as strings and builds aliases when they're needed.
set mgFilesFolder to (choose folder with prompt "Where are the files stored which you would like to move to the destination?")
set mgDestFolder to (choose folder with prompt "Where is the destination folder?")
--Always use System Events whenever possible. It's WAY faster than Finder.
tell application "System Events"
set folderList to name of folders of mgDestFolder
set fileList to name of files of mgFilesFolder
end tell
repeat with i from 1 to (count folderList)
set folderName to item i of folderList
set filesToMove to {}
repeat with j from 1 to (count fileList)
set filename to item j of fileList
if filename begins with folderName then
set end of filesToMove to alias ((mgFilesFolder as string) & filename)
end if
end repeat
--Can't use system events for moving files. You have to use Finder.
tell application "Finder"
move filesToMove to alias ((mgDestFolder as string) & folderName & ":")
end tell
end repeat
It might be easier to use shell scripting:
cd FOLDER1; for f in *; do d=../FOLDER2/"${f:0:7}"*; [[ -d $d ]] && mv "$f" "$d"; done

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 create and rename file from other files

In order to import .MOV files (h.264) to Final Cut Pro I need a correspoding .THM file with the same filename as the .MOV. Is it possible to do this with an AppleScript or Automator? Here is what I want to do:
Create a copy of a "TEMPLATE.THM" file that already exists on my HD
Rename the "TEMPLATE.THM" file using the .MOV filename
Do this to a folder of .MOV files to create a .THM file for every .MOV file both with the same filename.
G'day
This might not be the quickest way — but I see you're still waiting for an answer — so here's something to get you started. Select all your MOV files in the finder and run this in script editor.
set theTemplate to "Macintosh HD:Users:[user name]:[folder:location]:TEMPLATE.THM"
tell application "Finder"
set theFiles to selection
repeat with thisFile in theFiles
set thisName to name of thisFile
set theFolder to container of thisFile
set newFile to duplicate theTemplate to theFolder
set text item delimiters of AppleScript to "."
set thisName to text item 1 of thisName
set text item delimiters of AppleScript to ""
set newName to (thisName & ".THM")
set name of newFile to newName
end repeat
end tell
The easiest way to get the path to the template is to select it in the finder and run this :
tell application "Finder"
set theFile to selection as string
end tell
That will put the path in your results window — just copy it into the first line of the script above.
Hope that helps
m.

Resources