Applescript to find word in text file

Mac, How do you use applescript to find a word in a text file and if there is that word then it will do something, but if there isn't then it will do something else?


Solution 1:

In Unix, it is very easy to find words in files using tools like grep, awk, sed etc.

Here, I reckon, we can create a small shell script to find the word you want in a text file using grep and then we can call it directly from your AppleScript as shown below:

Solution 1 Putting the search keyword and filepath inside a shell script.

Let's call the shell script: find.sh:

#!/usr/bin/env bash

grep -w <search-word> "text-file-path"

Let's assume that we want to search for the word foo in a file called bar

Our shell script will look like this:

#!/usr/bin/env bash
grep -w "foo" "bar"

Note: grep -w will look for an exact match. For more info, look at man grep

Save the script find.sh in your working directory.

You can test it by:

bash find.sh

Now, you can call find.sh from your AppleScript like this:

try
  do shell script "bash /path-to/find.sh"
on error
  display dialog "no word found"
end try

It is needed to satisfy the sanity check by yourself, by making sure that you pass the correct filename and filepath (bar in our case) in your script.

Solution 2 Putting the search keyword and filepath inside your AppleScript.

If we can guarantee the sanity check of correct filepath, the shell script can be simplified further, especially if you want to put your search keyword and filepath in your AppleScript instead.

After simplification, find.sh will look like this:

#!/usr/bin/env bash
grep "$@"

Save the script find.sh in your working directory.

You can test it by:

bash find.sh "foo" "bar"

And your AppleScript will look something like this:

try
  do shell script "bash /path-to/find.sh -w 'foo' 'bar'"
on error
  display dialog "no word found"
end try

Solution 2:

Using a system grep is almost always going to be the fastest way to go, but if you want a pure AppleScript way to handle it, it's not hard:

on grep(myString, myFile)
    set fileHandle to open for access file myFile
    set theWords to words of (read fileHandle)
    close access fileHandle
    
    set matchCount to 0
    repeat with myWord in theWords
        if text of myWord is myString then set matchCount to matchCount + 1
    end repeat
    
    if (matchCount) > 0 then
        return true
    else
        return false
    end if
end grep

on run {}
    if grep("Overflow", "Users:jim:log.txt") then
        display dialog "Found it!"
    end if
end run

You could be a lot more efficient about this too, including breaking out of the repeat loop after finding the first match. But, this is very readable and you can build on this to do whatever you want.