How to get de newest path/filename of "~/Downloads/Relaties*"

-Newbie in Applescript-
I have one or more .csv files (tab delimited) on Downloads named “Relaties IMK *”.
How do I get the full filename of the newest of those files?

Is that literally an asterisk? Or are you using it as a wildcard, as in you have some files that might be named like this:

Relaties IMK A
Relaties IMK B
Relaties IMK C

sorry, should have stated that it’s meant as a wildcard.
basically something like the shell script
ls -r $(pwd)/Downloads/“${1}”* 2>- | head -1

Here’s a quick applescript that returns the newest file in the downloads folder that has “pdf” in its name.

Just change the value of search string to the string you’re looking for.

use AppleScript version "2.4" -- Yosemite (10.10) or later
use scripting additions
set findString to "pdf"
set downloadsFolder to path to downloads folder from user domain
tell application "Finder"
	set folderContents to every file of downloadsFolder as alias list
	set modDateToCompare to creation date of downloadsFolder
	set newestFileName to ""
	set newestFileAlias to ""
	repeat with thisFile in folderContents
		
		set fileName to name of thisFile
		if fileName contains findString then
			set thisModDate to modification date of thisFile
			if thisModDate > modDateToCompare then
				set modDateToCompare to thisModDate
				set newestFileName to name of thisFile
				set newestFileAlias to thisFile as alias
			end if
		end if
	end repeat
	set dialogPrompt to {¬
		("This is the newest file with “" & findString & "” in its name: "), ¬
		newestFileName, ¬
		newestFileAlias as text, ¬
		time string of modDateToCompare & " " & short date string of modDateToCompare}
	set AppleScript's text item delimiters to {return & return}
	set dialogPrompt to dialogPrompt as text
	set buttonList to {¬
		("Cancel"), ¬
		("Copy"), ¬
		("Okay") ¬
			}
	set DialogReply to display dialog dialogPrompt ¬
		with title ("Newest File") ¬
		buttons buttonList ¬
		default button 2 ¬
		cancel button 1 ¬
		giving up after 60
	if the button returned of DialogReply is "Copy" then set the clipboard to dialogPrompt
end tell


1 Like

The Finder will do this for you. You just need to ask:

tell application "Finder"
	set theFiles to every file of (path to downloads folder)
	set theSortedList to sort theFiles by modification date
	set theFileYouAreLookingFor to last item of theSortedList
end tell

you need last item since the files are sorted earliest, first, so the last item in the list is the newest one.

4 Likes

Hey, Camelot gave you a good solution, but it doesn’t filter for the name of the file. To do so you can add a whose clause:

tell application "Finder"
   set theFiles to every file of (path to downloads folder) whose name contains "pdf"
   set theSortedList to sort theFiles by modification date
   set theFileYouAreLookingFor to last item of theSortedList
end tell

That said, I’m not a big fan of the Finder’s sort command or its whose clause, because they slow things down.

The script I first posted takes less than 2 seconds to execute OMM.
Camelot’s script takes about 15 seconds, and with the whose clause modification over 18 seconds.

1 Like

Use System Events instead of Finder

The OP’s request has been answered, and I’ve included a shortcut solution below FWIW. The filter can be edited to return varying results. The timing result (excluding the alert dialog) with a folder that contained 500 files was 0.42 second.

Most Recently Created File.shortcut (22.7 KB)

1 Like

That’s a good point. System Events doesn’t have a sort command, so Camelot’s script wouldn’t work, but the script I posted works when modified and runs about twice as fast.

This thread has basic AppleScript and shortcut solutions, and I’ve included below an ASObjC solution. A few notes:

  • The search is case sensitive and does not return folders or packages.
  • The sort is by modification date but is easily changed to creation date.
  • The script can be made recursive by changing options:7 to options:6 .
  • The timing result when run on my home folder with the recursive option enabled was 14 milliseconds.

The OP has no need for this script, but perhaps it might be of use to someone in the future.

use framework "Foundation"
use scripting additions

set theFile to getFile("/Volumes/Store/Test Folder", "Test") --returns most recent file that begins with "Test"

on getFile(theFolder, matchString)
	set fileManager to current application's NSFileManager's defaultManager()
	set theFolder to current application's |NSURL|'s fileURLWithPath:theFolder
	set fileKey to current application's NSURLIsRegularFileKey
	set dateKey to current application's NSURLContentModificationDateKey --NSURLCreationDateKey if desired
	set pathKey to current application's NSURLPathKey
	set folderContents to (fileManager's enumeratorAtURL:theFolder includingPropertiesForKeys:{} options:7 errorHandler:(missing value))'s allObjects() -- change options 7 to 6 to descend into subfolders
	set thePredicate to current application's NSPredicate's predicateWithFormat_("lastPathComponent BEGINSWITH %@", matchString)
	set filteredFiles to folderContents's filteredArrayUsingPredicate:thePredicate
	set sortedFiles to current application's NSMutableArray's new()
	repeat with anItem in filteredFiles
		set {theResult, aRegularFile} to (anItem's getResourceValue:(reference) forKey:fileKey |error|:(missing value))
		if aRegularFile as boolean is true then (sortedFiles's addObject:(anItem's resourceValuesForKeys:{dateKey, pathKey} |error|:(missing value)))
	end repeat
	sortedFiles's sortUsingDescriptors:{current application's NSSortDescriptor's sortDescriptorWithKey:dateKey ascending:false}
	set thePaths to (sortedFiles's valueForKey:pathKey)
	if thePaths's |count|() is 0 then return "No matching files found"
	return (thePaths's objectAtIndex:0) as text
end getFile
1 Like