Get the Two Newest Files Inside All of the Subfolders

Hello everyone. I use KM for a bunch of simple stuff. Now I want to do something a little more complex.

I have a network volume where I have a year/month/day folder structure. What I want to do is to trigger KM manually for it to run through all the files inside all the subfolders and attach the two newest ones to a new email, no matter where they are.

I can find the solution on the forum to get the newest one. However, I couldn't manage to expand it from there to the newest two files.

Would anyone know how to do it?

Hey @martinewski,

The solution you found won't work, because the sort by date function doesn't work with the recursive option of the For-Each-Item-In-A-Directory action.

The macro below works by:

  • Recursively looping through the source directory – extracting the modification date and file path of the given item – and appending them to a variable.
  • It then sorts the variable.
  • It then reverses the lines in the variable.
  • The first two lines are isoloated.
  • Extraneous (date) data is removed.
  • Two path strings are returned.

Extract the Most Recently Modified Two Files in a Folder Hierarchy v1.00.kmmacros (11 KB)

Display-Macro-Image


Unfortunately this is slow if there are many, many files to loop through.

Let me know if it's fast enough for your needs.

If not then there are AppleScript and shell options that will be faster.

Unfortunately the Set Clipboard to File Reference action does not support multiple files.

@peternlewis – is there any chance you might adjust the action to work with 1 or more file paths?

The KM native email action does not support more than 1 attachment, so you'll have to use AppleScript to create your email and attach the files.

Let me know if you get stuck anywhere.

-Chris

1 Like

Oh, yeah.

I used modification date as the sort criteria for the files.

You have other options as well including add-date.

I just could't put up with Keyboard Maestro's speed on this one, so here's a version using find in an Execute a Shell Script action.

It blazes through my test directory of more than 25,000 items and many subdirectories in less than two seconds.


Extract the Most Recently Modified Two Files in a Folder Hierarchy (Shell) v1.00.kmmacros (6.7 KB)

Display-Macro-Image

Keyboard Maestro Export

7 Likes

Outstanding macro, so simple, yet very fast and efficient.

I’ve been learning a lot of bash lately, and will tuck this away to use and learn from.

1 Like

This is amazing. Thank you so much for providing the perfect solution.

1 Like