Applescript to find word in text file

applescript

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?

Best Answer

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