Filter a Variable to Get a Certain Line of Text

I'll most certainly kick myself when I see the solution. I haven't been KMing a lot and am not up to speed with approaches.

Thanx to @ccstone I've gotten a list of files in an embedded folder that have been modified in the last 1 hour – using an Execute a Shell Script action and the following code:

mdfind -onlyin ~/Dropbox/FMP/New_Server_BUs 'kMDItemContentModificationDate >= "$time.now(-1h)"'

Now how do I get the line out of that list that has the 'day name' and '.zip' in it.

Here is a sample list that is generated.

Dropbox 30 Min Thursday_2021-09-23_1000.zip
Driving_Dist V2 TK.fmp12
Cleaning Website Notes.fmp12
FileMaker Trainingx29.fmp12
FMServer_Sample.fmp12
Muffettas Domestic Assistants.fmp12
Client_Form_Short.fmp12
Service_Request.fmp12
MDA Postings.fmp12
Staff_Application_Long.fmp12
Regal_Recruiter TK.fmp12
RHS Invoices.fmp12
MDA Phone Intake.fmp12
Client_Form_Long.fmp12
z_email_app.fmp12
Toolkit.fmp12
Staff_Application_Short.fmp12
RHS Invoices ORIG.fmp12

So I'd like to get the line:

⠀⠀ Dropbox 30 Min Thursday_2021-09-23_1000.zip

Into a separate variable (or into the same variable) when today is Thursday.

Greatly appreciate any help.

How about this:

To get the current day of the week: %ICUDateTime%EEEE%

The RegEx expression is:

(?m)^(.*%Variable%Local_Day%_\d{4}-\d{2}-\d{2}_\d*\.zip)$

If you want an explanation of the RegEx string, let me know.

NOTES:

  • I'm not sure what the number is before the extension, but this expression allows any number of digits in that number.
  • This will return the first hit only. Not sure how to do multiple hits, except to use a "For Each Line..." action and check each line.
  • If the "Search Variable" action doesn't find a hit, the default is to abort with an error message. You can change this through the "Gear" icon menu.

Hope this helps.

2 Likes

Hey Troy,

I'm in a Bash kind of mood today, so here's a very terse macro.

NOTES:

  • The RegEx looks for Today's Long Weekday name followed by an underscore, a date string, and skipping to a “.zip” suffix at the end.

  • If there are more than one Today .zip files it will print all of them.

-Chris


Extract Today's Zip File from From File Name List v1.01.kmmacros (6.1 KB)
Keyboard Maestro Export

1 Like

Wow Dan, thank you so much, really, I am very grateful for your time and expertise - I will be working away with it now. THANK YOUI

1 Like

Man Chris, you are a monster... the other monster on this Forum, Dan replied as you can see. I just want to thank you for your time and expertise... in a Bash mood!!! =), I will be working away with this solution. You guys are awesome, really!

2 Likes

The advantage of @ccstone's method is it returns all matching lines, so if it were me, I'd probably use his method. :grinning_face_with_smiling_eyes:

1 Like

WOOF, They both work like a charm, I am not surprised.... just awesome,,,, !!!!!!
Thank you @ccstone and @DanThomas -
I'm now able to upload a zip file of all my FMP databases to a separate (unseen to the local user) dropbox account via filemaker pro. Crazy.... - cheers

FWIW, an Execute JavaScript for Automation action approach, steering away from Regex complexity:

(() => {
    "use strict";

    return Application("Keyboard Maestro Engine")
        .getvariable("sampleLines")
        .split(/[\r\n]+/u)
        .filter(x => x.endsWith(".zip"))
        .join("\n");
})();
3 Likes

What about his other filter criteria?

his other filter criteria?

Not yet completely clear to me what they are : -)

( I'd have to see a slightly more explicit definition of the pattern )

At the moment we have "the line which", and termination with ".zip" suffices to pick that element from the given set ...

We can, of course, introduce whatever the minimum required dose of:

  • parser combinators
  • regex patterns
  • simple string predicates

turns out to be.

"the absolute minimum that works" is always a good place to start, I think.

Perhaps worth holding back from elaborated patterns until we are sure what that minimum is ?

(Premature specification can, of course, introduce false negatives)

Usually I'm the one who misses the details in someone's post. Thanks for helping me not feel so alone. :wink:

If your goal is "the absolute minimum that works ", you should at least include checking for the day.

Honestly, the only reason I replied to your post at all was your comment:

Perhaps worth holding back from elaborated patterns until we are sure what that minimum is ?

The only "elaborated pattern" either of us included was checking to make sure the file name included a date in it, which wasn't specifically asked for, but it's not an unreasonable assumption.

In the end, though, I can already see this is going to devolve into something I don't really care about, so I'm out.

2 Likes

should at least

Irritated tone ? Is something going on that I have missed ?
But FWIW, if you think the pattern is something like:

any space-delimited token which starts with `Thursday` and ends with `.zip`

(Not yet clear to me if that's really what's needed in the user data)

then you could, perhaps begin to elaborate and test in JS by writing something like:

(() => {
    "use strict";

    return Application("Keyboard Maestro Engine")
        .getvariable("sampleLines")
        // Lines
        .split(/[\r\n]+/u)
        .map(
            x => x
            // Words / tokens
            .split(/\s+/u)
            .filter(w => w.startsWith("Thursday") && w.endsWith(".zip"))
        )
        .join("\n");
})();
1 Like

Hey Rob,

While I'm quite happy to see this method of filtering with JavaScript, it still doesn't meet @troy's stated requirements.

The target file name does not start with “Thursday”; it contains “Thursday” and ends with “.zip”.

Dropbox 30 Min Thursday_2021-09-23_1000.zip

A variation on the theme that works is:

// Simulate Keyboard Maestro Variable
function fileNameList() {

const fileNameList = `
Dropbox 30 Min Thursday_2021-09-23_1000.zip
Driving_Dist V2 TK.fmp12
Cleaning Website Notes.fmp12
FileMaker Trainingx29.fmp12
FMServer_Sample.fmp12
Muffettas Domestic Assistants.fmp12
Client_Form_Short.fmp12
Service_Request.fmp12
MDA Postings.fmp12
Staff_Application_Long.fmp12
Regal_Recruiter TK.fmp12
RHS Invoices.fmp12
MDA Phone Intake.fmp12
Client_Form_Long.fmp12
z_email_app.fmp12
Toolkit.fmp12
Staff_Application_Short.fmp12
RHS Invoices ORIG.fmp12
`;

return fileNameList.substr(1, fileNameList.length -2)

}

(() => {
   "use strict";

   return fileNameList()
      .split(/[\r\n]+/u)
      .filter(theLine => theLine.includes("Thursday")
         && theLine.endsWith(".zip"))
      .join("\n");

})();

Macro:

JXA to Extract a File Name from a Text List Containing “Thursday” and Ending with “.zip” v1.00.kmmacros (6.3 KB)

Macro Image

Keyboard Maestro Export

-Chris

2 Likes

The file name doesn't but the space-separated token does – hence the segmentation of each line (see code above) into space-delimited tokens.

(We probably need a more formal spec or a larger data sample though)

Hey Folks,

My script and macro in Post #13 above does not automatically compute the current long weekday name.

I've added that and used a regex match() filter in the JavaScript.

The script runs as-is in the Script Editor.app or a KM JXA action.

JavaScript (JXA) Script
// --------------------------------------------------------
// Auth: Christopher Stone
// dCre: 2021/09/26 00:38
// dMod: 2021/09/26 00:38 
// Appl: Extract File Name from Text List Where Name Contains
//       Today's Long Weekday Name and Ends with ".zip"
// Task: 
// Libs: None
// Osax: None
// Tags: @Applescript, @Script, @JavaScript, @JXA, @Extract, @File_Name
// --------------------------------------------------------

// Simulate Keyboard Maestro Variable
function fileNameList() {

// NOTE -- Change 'Sunday' in first line to Today's Name Before Executing.
const fileNameList = `
Dropbox 30 Min Sunday_2021-09-23_1000.zip
Driving_Dist V2 TK.fmp12
Cleaning Website Notes.fmp12
FileMaker Trainingx29.fmp12
FMServer_Sample.fmp12
Muffettas Domestic Assistants.fmp12
Client_Form_Short.fmp12
Service_Request.fmp12
MDA Postings.fmp12
Staff_Application_Long.fmp12
Regal_Recruiter TK.fmp12
RHS Invoices.fmp12
MDA Phone Intake.fmp12
Client_Form_Long.fmp12
z_email_app.fmp12
Toolkit.fmp12
Staff_Application_Short.fmp12
RHS Invoices ORIG.fmp12
`;

return fileNameList.substr(1, fileNameList.length -2)

}

// --------------------------------------------------------

function getLongWeekDay() {
   return new Date().toLocaleString('en-us', { weekday: 'long' });
}

// --------------------------------------------------------

(() => {
   "use strict";
   
   const regEx = new RegExp(getLongWeekDay() + '.+\.zip$')

   // ----------------------------------------------------
   // Using a regular expression based filter - match()
   // ----------------------------------------------------

   return fileNameList()
      .split(/[\r\n]+/u)
      .filter(theLine => theLine.match(regEx))
      .join("\n");

})();

// --------------------------------------------------------

I've also included a Keyboard Maestro macro that gets its data from a KM variable.

Macro

JXA to Extract a File Name from a Text List Containing “Thursday” and Ending with “.zip” v1.01.kmmacros (8.0 KB)

-Chris

3 Likes

Hey @troy,

I have a feeling you're doing something the hard way here.

To get the path of your backup file you really only need one line of code in an Execute a Shell Script action.

Find Today's FMP Backup Zip File v1.00.kmmacros (8.4 KB)

Macro-Image

I think I can do the same with mdls, but find is a tried and true Unix tool.

I'll fiddle with it a bit more later if I have time and gumption. (Found some.)

mdfind -onlyin ~/Dropbox/FMP/New_Server_BUs 'kMDItemContentModificationDate >= $time.now(-1h) && kMDItemFSName == *'$(date '+%A')'*'

I guess I'm done now.  :sunglasses:

-Chris

1 Like

Perfect, I just changed to -30m, works like a charm....
Can't thank you enough for all of your time....
Cheers,

1 Like

Hey Folks,

Since other people are likely to need to accomplish this task or something like it, I thought we should add in an entirely Keyboard Maestro native version for users who are never likely to embrace scripting.

This was not very difficult (for me), although it was a little more involved than I thought it was going to be – and someone not very familiar with Keyboard Maestro would be scratching their head.

Hopefully the macro as constructed is easy enough to follow, but I'm open to question if anyone has problems with it.

I guess I'm really done now. :sunglasses:

-Chris


Find Today's FMP Backup Zip File (KM-Native) v1.00.kmmacros (11 KB)

Macro-Image


1 Like

Hey Folks,

Worth noting – a quick synopsis.

I believe all the listed parameters work.

find ~/Dropbox/FMP/New_Server_BUs -type f -mtime -30m -iname "*$(date '+%A')*.zip"
 30m  ==  Exactly 30 minutes.
-30m  ==  30 minutes or less.
+30m  ==  30 minutes or more.

Just to give context to +, -, and none.

There's tons of information about Unix's find command on the net, but some of it will make your head spin.

-Chris

1 Like