AppleScript to convert NEF to JPG preserving Creation Date/Time - image

I have a Nikon camera that outputs great NEF raw files, and not so great JPEG files. I can use the Preview app that came with my Mac OSX 10.6.8 (Snow Leopard) to simply open a NEF and SaveAs JPEG to create a file about 1/6 the size that is virtually indistinguishable from the original NEF.
[EDIT] Here is the final script that works as desired, with comments and some error testing:
(*
AppleScript to convert Nikon raw NEF files into much smaller JPG files.
The JPG files will inherit the file date and time of the source NEF files.
Note that any JPG files in the target folder that have the same name
as a NEF file in that folder, will be overwritten.
*)
-- User selects target folder with NEF files to convert and save there.
set theImageFolder to choose folder with prompt "
Select a folder containing fileⁿ.NEF images to
convert into JPEG images and SaveAs: fileⁿ.JPG"
set theOutputFolder to theImageFolder
-- Finder locates NEF files, ignoring other file types in the target folder.
tell application "Finder"
set theImages to every file of theImageFolder whose name extension is "NEF"
end tell
-- Image Events app processes the images.
tell application "Image Events"
launch
repeat with a from 1 to length of theImages
-- Get file name as text string.
set theImage to file ((item a of theImages) as string)
-- Get date/time of source NEF file.
tell application "Finder" to set fileTimestamp to creation date of theImage
set theImageReference to open theImage
tell theImageReference
set theImageName to name
-- Detect the .NEF extension to replace with .JPG on output.
set savedDelimiters to AppleScript's text item delimiters
-- Split filename string into list, using "." as a delimiter.
set AppleScript's text item delimiters to {"."}
set delimitedList to every text item of theImageName
-- Remove the .NEF extension from the list, if it was there.
ignoring case
--Process only NEF files.
if last item of delimitedList is "NEF" then
set filenameList to items 1 thru -2 of delimitedList
set theImageName to filenameList as string
end if
end ignoring
-- Restore delimiters to default in case it had previously been changed.
set AppleScript's text item delimiters to savedDelimiters
-- Construct full path of file to save, with JPG as output file extension.
set saveImageName to ((theOutputFolder as string) & theImageName & ".JPG")
-- Check if a file with the output JPG file name is already present in the target folder.
tell application "Finder"
if exists file saveImageName then
-- Abort script if user doesn't want to overwrite this file and continue.
beep
if button returned of (display dialog " An identical JPG file is already at:
" & saveImageName & "
Would you like to:" buttons {"Replace it and continue", "Abort"} default button "Abort") is "Abort" then exit repeat
end if
end tell
-- SaveAs the file in JPEG format, leaving the source NEF file unmodified.
set saveImageName to save in saveImageName as JPEG
--Match the output JPG file date/time to that of the NEF source file.
tell application "Finder" to set modification date of saveImageName to fileTimestamp
end tell
end repeat
end tell
tell application "Finder"
display alert "Done. Duplicated selected NEF files in
" & theOutputFolder & "
as JPGs with dates/times matching NEFs."
end tell
Below was my initial attempt to create an AppleScript to spare me the hours it would take to do this manually with the Preview app on my hundreds of NEF files. It works, but the helpful folks on this website helped me to greatly improve it. As you can see from the initial user prompt, I wanted to prompt the user only in the event that an existing JPG file will be replaced. I also wanted to have the output file names be n.JPG rather than n.NEF.jpg and have the output JPG file inherit the original NEF file's Creation Date & Time. I welcomed any suggestions, though since I'd already come this far my preference was to refrain from adding shell scripts and do it all with AppleScript if possible.
set theImageFolder to choose folder with prompt "Note: This script will replace any existing files in the selected folder matching
the name of a NEF file and end in a JPG extension with a new file of that name.
For example, X.NEF will create X.JPG and replace any existing file named X.JPG
that was already in the selected folder (not in any other folders). To begin now,
Select a folder with NEF images to convert into JPEG images:"
set theOutputFolder to theImageFolder
tell application "Finder"
set theImages to every file of theImageFolder whose name extension is "NEF"
end tell
tell application "Image Events"
launch
repeat with a from 1 to length of theImages
set theImage to file ((item a of theImages) as string)
set theImageReference to open theImage
tell theImageReference
set theImageName to name
save in ((theOutputFolder as string) & theImageName & ".JPG") as JPEG
end tell
end repeat
end tell
tell application "Finder"
display alert "Done. All NEF files in the selected folder have been duplicated in JPEG format."
end tell

Thank you so much, Atomic Toothbrush!
I can't seem to insert a blank line to a Comment or mark as Code here without it saving the Comment, so here's a followup as an Answer. Really it's more of a revised Question. :}
Seems to me it's very close to working as hoped. I replaced the code inside the Repeat section with the fascinating snippet you suggested, though I don't yet fully understand the tricks it's doing. With one file in the target folder the script aborts highlighting the word "alias" with this message:
error "File Art:Users:me:Desktop:scriptTest:-file:DSC_2070.JPG wasn’t found." number -43 from "Art:Users:me:Desktop:scriptTest:-file:DSC_2070.JPG"
With two files in the target folder and the "as alias" removed, it creates DSC_2070.JPG just fine but doesn't change the mod date and aborts with this message:
error "Can’t set modification date of \"Art:Users:me:Desktop:scriptTest:-file:DSC_2070.JPG\" to date \"Wednesday, August 28, 2013 1:03:29 PM\"." number -10006 from modification date of "Art:Users:me:Desktop:scriptTest:-file:DSC_2070.JPG"
If I run it once to create the JPG file as above, then add the "as alias" back in and run it again it does change the date (for both creation and modification!) to match the source file but then aborts highlighting the last Tell inside the Repeat with this message:
error "File Art:Users:me:Desktop:scriptTest:-file:DSC_2070.JPG wasn’t found." number -43 from "Art:Users:me:Desktop:scriptTest:-file:DSC_2070.JPG"
Looks like it's remembering the last file processed because if I rename the file, remove the "as alias" and run it again it aborts highlighting that same last Tell line inside the Repeat with this message referencing the file name that's no longer in the folder:
error "Can’t set modification date of \"Art:Users:me:Desktop:scriptTest:-file:DSC_2070.JPG\" to date \"Wednesday, August 28, 2013 1:14:19 PM\"." number -10006 from modification date of "Art:Users:me:Desktop:scriptTest:-file:DSC_2070.JPG"
Complete script with Repeat string inserted as tested above:
set theImageFolder to choose folder with prompt "Select a folder with NEF images to convert into JPEG images:"
set theOutputFolder to theImageFolder
tell application "Finder"
set theImages to every file of theImageFolder whose name extension is "NEF"
end tell
tell application "Image Events"
launch
repeat with a from 1 to length of theImages
set theImage to file ((item a of theImages) as string)
tell application "Finder" to set fileTimestamp to creation date of theImage
set theImageReference to open theImage
tell theImageReference
set theImageName to name
set savedDelimiters to AppleScript's text item delimiters
set AppleScript's text item delimiters to {"."}
set delimitedList to every text item of theImageName
ignoring case
if last item of delimitedList is "NEF" then
set filenameList to items 1 thru -2 of delimitedList
set theImageName to filenameList as string
end if
end ignoring
set AppleScript's text item delimiters to savedDelimiters
set saveImageName to ((theOutputFolder as string) & theImageName & ".JPG") as alias
save in saveImageName as JPEG
tell application "Finder" to set modification date of saveImageName to fileTimestamp
end tell
end repeat
end tell
tell application "Finder"
display alert "Done. All NEF files in the selected folder have been duplicated in JPEG format with modification date and time changed to match the NEF source file."
end tell

You could also use sips to convert the images and touch -r to change the modification (and creation) times:
for f in *.nef; do jpg="${f%nef}jpg"; sips -s format jpeg -s formatOptions 90 "$f" -o "$jpg"; touch -r "$f" "$jpg"; done
touch -r normally changes only the modification and access times, but it also changes the creation time if the target time is before the original creation time.
If the files have different creation and modification times, you can use SetFile and GetFileInfo:
SetFile -m "$(GetFileInfo -m "$f")" "$jpg"; SetFile -d "$(GetFileInfo -d "$f")" "$jpg"
-m changes the modification time and -d changes the creation time. SetFile and GetFileInfo are part of the command line tools package that can be downloaded from developer.apple.com/downloads or from Xcode's preferences.

From the filename point of view, it sounds like you just need to strip the .NEF extension from the filename. You can do this by turning the filename string into a list, using "." as a delimiter, remove the last item from the list, then reassemble the list to the filename string. I think this should do it (inserted into "repeat" block):
set theImage to file ((item a of theImages) as string)
tell application "Finder" to set fileTimestamp to creation date of theImage
set theImageReference to open theImage
tell theImageReference
set theImageName to name
set savedDelimiters to AppleScript's text item delimiters
-- Split filename string into list, using "." as a delimiter
set AppleScript's text item delimiters to {"."}
set delimitedList to every text item of theImageName
-- Remove the .NEF extension from the list, if it was there
ignoring case
if last item of delimitedList is "NEF" then
set filenameList to items 1 thru -2 of delimitedList
set theImageName to filenameList as string
end if
end ignoring
-- Restore delimiters to default in case of other users
set AppleScript's text item delimiters to savedDelimiters
-- Construct full path of file to save
set saveImageName to ((theOutputFolder as string) & theImageName & ".JPG")
-- Check for file existence
tell application "Finder"
if exists file saveImageName then
-- Check with user - skip to the next file if user doesn't want to overwrite
if button returned of (display dialog saveImageName & " already exists. Overwrite?" buttons {"Yes", "No"}) is "No" then exit repeat
end if
end tell
-- Save the file
set saveImageName to save in saveImageName as JPEG
-- Fiddle the timestamp of the saved file
tell application "Finder" to set modification date of saveImageName to fileTimestamp
end tell
Note I don't think you can easily change t)he creation date on the .JPG file (it is a r/o property in the finder dictionary. The best I can do is set the modification date of the .JPG file to the creation date of the .NEF file.

Related

AppleScript Keynote hangup after opening a illegal pptx file

first I am a beginner AppleScript developer. and I have searched this question for a long time but no result found. I have an AppleScript to convert ppt files into pdf format. but the script will hangup after it matches a bad ppt file.
the script/keynote will popup a dialog showing "xxx.ppt can't be opened right now" "the file format is invalid".
is there any way to prevent keynote from popping up this kinds of dialog?
below is the sample code, and file is a image file but I changed extension to pptx to simulate an illegle file:
set thefile to POSIX file "/Users/dazhangluo/Downloads/brain-storming.pptx"
tell application "Keynote"
activate
try
set thedoc to open thefile
--display dialog class of thedoc
on error errMessage
--display dialog errMessage
log errorMessage
end try
end tell
There is a command-line tool called exiftool which can inspect files and get their metadata, including the 'file type' tag (using -filetype). There are a variety of ways to install it†. Unlike 'mdls', it isn't easily fooled by the file extension. If you run it on a pptx file, it will include this in its results:
File Type : PPTX
You can then grab the last word to test. This script will loop through the files in the specified folder, use exiftool to extract their file type, and then copy the alias of any matching file to a new list. It then opens each file in keynote. My version of keynote (v8) doesn't let me script anything with powerpoint documents, so you're on your own at that point.
set srcFol to (path to desktop as text) & "presentations" as alias
-- or if you prefer…
-- set srcFol to choose folder
tell application "Finder"
set fList to files of srcFol as alias list
set cleanList to {}
repeat with f in fList
set ppFile to POSIX path of f
set qfFile to quoted form of ppFile
tell me to set exifData to do shell script "/usr/local/bin/exiftool -filetype " & qfFile
if last word of exifData is "PPTX" then
set end of cleanList to contents of f
--> alias "Mac:Users:username:Desktop:presentations:powerpoint1.pptx"
end if
end repeat
end tell
tell application "Keynote"
activate
repeat with pptxFile in cleanList
open pptxFile
-- do whatever
end repeat
end tell
NB † Depending upon where exiftool is installed, you may need to change the path, which you can get with which exiftool.

Batch Convert *.numbers to *.csv AppleScript

I was looking for a script that would batch convert all *.numbers files in a given folder to *.csv files.
I found the following on GitHub and added an additional line as suggested in the comments suggestion. When I run the script, Numbers launches and opens the test file from the folder specified - but the file is not exported. Numbers just stays open and terminal errors out with:
/Users/Shared/Untitled.scpt: execution error: Numbers got an error: Invalid key form. (-10002)
The script (located in /Users/Shared) has the following permissions:
-rwxr-xr-x
#!/usr/bin/osascript
on run argv
set theFilePath to POSIX file (item 1 of argv)
set theFolder to theFilePath as alias
tell application "Finder" to set theDocs to theFolder's items
-- Avoid export privilege problem
set privilegeFile to (theFolder as text) & ".permission"
close access (open for access privilegeFile)
repeat with aDoc in theDocs
set docName to aDoc's name as text
if docName ends with ".numbers" then
set exportName to (theFolder as text) & docName
set exportName to exportName's text 1 thru -9
set exportName to (exportName & "csv")
tell application "Numbers"
open aDoc
delay 5 -- may need to adjust this higher
tell front document
export to file exportName as CSV
close
end tell
end tell
end if
end repeat
end run
Any suggestions?
Here is what I did and works for me in macOS High Sierra:
In Terminal:
touch numb2csv; open -e numb2csv; chmod +x numb2csv
• This creates an empty ASCII Text file named numb2csv.
• Opens, by default, numb2csv in TextEdit.
• Makes the numb2csv file executable.
Copy and paste the example AppleScript code, shown further below, into the opened numb2csv file.
Save and close the numb2csv file.
In Terminal executed the numb2csv executable file, e.g.:
./numb2csv "$HOME/Documents"
This created a CSV file of the same name as each Numbers document in my Documents folder, not traversing any nested folders.
Example AppleScript code:
#!/usr/bin/osascript
on run argv
set theFilePath to POSIX file (item 1 of argv)
set theFolder to theFilePath as alias
tell application "System Events" to set theDocs to theFolder's items whose name extension = "numbers"
repeat with aDoc in theDocs
set docName to aDoc's name as text
set exportName to (theFolder as text) & docName
set exportName to exportName's text 1 thru -8
set exportName to (exportName & "csv")
tell application "Numbers"
launch
open aDoc
repeat until exists document 1
delay 3
end repeat
tell front document
export to file exportName as CSV
close
end tell
end tell
end repeat
tell application "Numbers" to quit
end run
NOTE: As coded, this will overwrite an existing CSV file of the same name as each Numbers file processed, if they already exist. Additional coding required if wanting to not overwrite existing files
If you receive the Script Error:
Numbers got an error: The document “name” could not be exported as “name”. You don’t have permission.
It is my experience that the Numbers document was not fully opened prior to being exported and that increasing the value of the delay command resolves this issue. This is of course assuming that one actually has write permissions in the folder the target Numbers documents exists.
Or one can introduce an error handler within the tell front document block which, if my theory is right about the target document not being fully loaded before the export, will give additional time, e.g.:
Change:
tell front document
export to file exportName as CSV
close
end tell
To:
tell front document
try
export to file exportName as CSV
close
on error
delay 3
export to file exportName as CSV
close
end try
end tell
Note: The primary example AppleScript code is just that and does not contain any error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors. See included example directly above.
I was looking for that, unfortunately, that doesn’t work anymore.
This line
tell application "System Events" to set theDocs to theFolder's items whose name extension = "numbers"
Gets the following error:
execution error: Can’t make file "file.numbers" of application "System Events" into the expected type. (-1700)
macOs Big Sur Versio 11.01
automator version 2.10
Numbers version 10.3.5
Inspired by this thread and those articles Exporting Numbers Documents and Get full directory contents with AppleScript
The following code works:
#!/usr/bin/osascript
log "Start"
property exportFileExtension : "csv"
tell application "Finder"
activate
set sourceFolder to choose folder with prompt "Please select directory."
set fileList to name of every file of sourceFolder
end tell
set the defaultDestinationFolder to sourceFolder
repeat with documentName in fileList
log "documentName: " & documentName
set fullPath to (sourceFolder as text) & documentName
log "fullPath: " & fullPath
if documentName ends with ".numbers" then
set documentName to text 1 thru -9 of documentName
tell application "Finder"
set newExportItemName to documentName & "." & exportFileExtension
set incrementIndex to 1
repeat until not (exists document file newExportItemName of defaultDestinationFolder)
set newExportItemName to ¬
documentName & "-" & (incrementIndex as string) & "." & exportFileExtension
set incrementIndex to incrementIndex + 1
end repeat
end tell
set the targetFileHFSPath to ¬
(defaultDestinationFolder as string) & newExportItemName
tell application "Numbers"
launch
open fullPath
with timeout of 1200 seconds
export front document to file targetFileHFSPath as CSV
end timeout
close
end tell
end if
end repeat
user3439894's answer works with a few change:
exists document 1 => number of documents > 0

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

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

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