So I have a database of folders and files (.txt) and I'm trying to create a program that I can enter keywords and have it search those files, and it will output the text of any files containing the keywords. I have a working code that does just that, but it doesn't search the words individually - it searches for the words together, as a single string.

For instance, if I input "Joe Bill Bob," I'd like it to output files that contain each of those words anywhere in the file, even if they aren't next to each other, or in that order.

I would rather avoid doing a repeat loop to input one search term at a time.

I'd also rather avoid setting up hundreds of variables in the code, and do a repeat loop that if a character isn't a space it adds it onto the first blank variable and if it is it skips to the next variable.

If you have any other ideas, that would be great. Thanks!

  • What types of files are you looking for (Plain text only, or there are several types (like PDF, RTF, RTFD))? Add your current script in the question. – jackjr300 Aug 7 '17 at 19:13
  • @jackjr300 On the piece that I'm asking about, there is no script as of yet. I don't even know where I would start. The files are .txt - edited that into the question. – DonielF Aug 7 '17 at 19:16

Note: the text files must be encoded with the "UTF8" encoding.

Here's a starting script:

Example: The keywords:


fgrep and sort return lines, like this :


The script use a loop to check the path of each item in this list.

The script get the path from the first item, it remove ":Bill" at end of the line --> so the path is "/path/of/thisFile.txt".

The script check the item (current index + the number of keywords -1), it's the third item, so the third item contains the same path, then the script append the path into a new list

The others items doesn't contains all the keywords.

set r to text returned of (display dialog "What keywords?" default answer "Joe Bill Bob") --- each keyword must be sepearated by a space
set tKeys to my makeKeysForGrep(r)
if tKeys is not "" then
    set masterFolder to choose folder with prompt "Select the source folder .."
    set filesList to my getFilescontainingKeywords(masterFolder, tKeys) -- get a list of files ( each file contains all the keywords)
    --do something with the filesList -- this list contains path of type 'posix path' 
end if

on makeKeysForGrep(t)
    (***   delete trailing and leading spaces, replace multiple spaces in a row by one space (clean the string to avoid issue with the unnecessary spaces in the grep command),
     and replace the space character by a linefeed character , so each line contains a keyword.  ***)
    set r to do shell script "perl -pe 's/ +$|^ +//g; s/ +/ /g; s/ /\\n/g; '  <<< " & (quoted form of t) & "| sort -u" without altering line endings
    if r is not linefeed then return text 1 thru -2 of r -- remove the last line (it's a blank line)
    return "" -- r is a a blank line, so return ""
end makeKeysForGrep

on getFilescontainingKeywords(dir, tKeys)
    script o
        property tfiles : {}
    end script
    set numOfKeywords to count (paragraphs of tKeys) -- get the number of keywords
    set tFolder to quoted form of POSIX path of dir
    set o's tfiles to do shell script "fgrep -R -o -w  --include \"*.txt\" " & (quoted form of tKeys) & " " & tFolder & " | sort -u"
    -- fgrep return the full path + ":" + the keyword, sort -u  : sort the paths and deletes duplicate lines (because the same file can contains multiple occcurences of a keyword)

    if o's tfiles is not "" then
        if numOfKeywords = 1 then return o's tfiles -- no need to continue because one keyword only,  return all Files
        set l to {}
        set o's tfiles to paragraphs of o's tfiles
        set tc to count o's tfiles
        set firstKeyword to ":" & (paragraph 1 of tKeys)
        set numCh to (length of firstKeyword) + 1
        set i to 1
        repeat while (i < tc) -- check each path in the list, the same path must exists  numOfKeywords  in a row 
            set thisItem to (item i of o's tfiles)
            if thisItem ends with firstKeyword then
                set textFilepath to text 1 thru -numCh of thisItem
                set j to (i + numOfKeywords - 1)
                if j > tc then exit repeat
                if (item j of o's tfiles) starts with textFilepath then -- this file contains all the keywords
                    set end of l to textFilepath --- append this path to the list
                    set i to i + numOfKeywords -- to skip items wich contains the same path
                    set i to i + 1 -- next file
                end if
                set i to i + 1 -- next file
            end if
        end repeat
        return l -- list of files which contains all the keywords
    end if
    return {} -- No files found
end getFilescontainingKeywords

The options of fgrep :

  • The --include \"*.txt\" option : only files matching the given filename pattern are searched, so any name which end with ".txt"

    The -w option : match word only, so Bob does not match Bobby, remove this option if you want to match a substring in the text.

    The -R option : Recursively search subdirectories, remove this option if you don't want recursion.

    Add the -i option to perform case insensitive matching. By default, fgrep is case sensitive.

| improve this answer | |

You might not even need AppleScript. Finder supports Boolean searches as an advanced function. You can save a search and reuse it or make them ad-hoc as your needs change.

A Boolean query uses AND, OR, and NOT (known as Boolean operators) to narrow search results. You can also use a minus sign (–), which means AND NOT, to exclude items when you search.

Your ordering clause will be problematic since spotlight doesn’t expose (or doesn’t seven consider in the first place) order of results - just that the string exists in the file.

| improve this answer | |
  • For various reasons I'd rather an option that works in AppleScript, without resorting to Spotlight. – DonielF Aug 6 '17 at 19:43
  • 4
    For what reason do you specifically need AppleScript? – William T Froggard Aug 7 '17 at 1:12
  • 3
    Also, it's worth noting that even if your use-case actually calls for custom code, it's highly likely that AppleScript will not be the best language to write this in, because AppleScript doesn't have anywhere near the level of functionality that more widely used languages such as Python do. It's more of a question of which tool is right for the job. – William T Froggard Aug 7 '17 at 1:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .