How to Use "Does Text Exist in File?" as an "If, Then, Else" Condition

A while ago I was wanting a way to process a file differently depending on whether or not it included specific text. It seemed to me that this "ought to" be a built-in condition or function in KBM, but I wasn't been able to find it, not then and not again while searching now.

Previously, I finally settled for using Execute Shell Script to run GREP on the file and save the result in a KBM variable. Then I tested the contents of the resulting variable in my "If, Then, Else" group.

It worked, so I went on. But it felt like going the long way 'round the barn. I had a similar situation recently and again I pored through the manual and the Forum and found nothing. I wanted to use one simple RE if the file contained on thing and another simple RE if the file had different contents. This time I was able to do what I needed by using a more complex Regular Expression in the KBM Search and Replace action, but the question is still there, so I'm asking.

What is the simplest way within KBM to have the presence or absence of something in a file be the conditional test in an If, Then, Else group?

How about this @August ?

Test Text Exist.kmmacros (3.1 KB)

Click to see macro

3 Likes

Thanks @tiffle,

The concept of "Read File to Variable" just did not occur to me. I'm looking at text files of 150MB or more and it seems to my naive sensibilities to be a waste of system resources.

Should you have a step where you delete that variable after you're done with it? Or set it to be "local" so that it is removed after the macro ends?

How big is that Thesaurus file you test on?

This :point_up_2:t3:, as in @tiffle's suggestion.

2 Likes

No matter what app, utility, or programming language you use to detect specific contents in a file the file will have to be read. Some methods just do this more transparently than others.

As long as you're using local variables you shouldn't have any major problems reading such tiny files.

1 Like

It’s 35MB. And from my (the user’s) POV the macro runs instantaneously.

If you don’t want a variable to “take up room” when a macro’s finished, use a local variable as others have already said :grinning: and I demonstrate in my example.

Hey - if you don’t use those resources that’s a waste too isn’t it?

2 Likes

If you don't want to explicitly read to a variable you could do something like this:

Whether that's any faster/less resource intensive will depend on how things are implemented behind-the-scenes.

It really depends on what you do after the search. If you're going to manipulate the file contents on a match, probably best to read into a variable rather than read it once to check and again to manipulate.

But on modern machines I doubt you'd see much difference -- unless you're talking GBs of text...

3 Likes