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?
Applescript to find word in text file
applescript
Related Question
- AppleScript Text Delimiter for most recent text
- AppleScript MS Office – Set Text Style in MS Word via AppleScript
- How to insert a Word (or cvs) document or Video file to a Word document with AppleScript
- AppleScript – Automate MS Word for Mac to Add Quote Mark Wrapper to Unformatted Text Paste
- AppleScript to perform actions to text in new TextEdit document
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
:Let's assume that we want to search for the word
foo
in a file calledbar
Our shell script will look like this:
Note:
grep -w
will look for an exact match. For more info, look atman grep
Save the script
find.sh
in your working directory.You can test it by:
Now, you can call
find.sh
from your AppleScript like this: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:Save the script
find.sh
in your working directory.You can test it by:
And your AppleScript will look something like this: