AppleScript – mdfind kMDItemTextContent script to find specified content from display dialog query

applescript

I have this AppleScript find all documents whose content matches the text 'theMessage' and it works perfectly fine:

set matchText to paragraphs of (do shell script "mdfind \"kMDItemTextContent == 'theMessage'\"")
set targetMatch to (choose from list matchText) as string
if targetMatch ≠ "false" then tell application "Finder" to open (POSIX file targetMatch) as alias

but I would like to improve it so that I can search for any text I specify

For example:

set searchText to text returned of (display dialog "Enter your search text:" default answer "")

and then continue on with previous script, with this simple change:

set matchText to paragraphs of (do shell script "mdfind \"kMDItemTextContent == searchText\"")

I just can't seem to get it to take searchText as a variable

Best Answer

Try:

set searchText to text returned of (display dialog "Enter your search text:" default answer "")
set matchText to paragraphs of (do shell script "mdfind \"kMDItemTextContent == " & quoted form of searchText & "\"")
if matchText ≠ {} then
    set targetMatch to (choose from list matchText) as string
    if targetMatch ≠ "false" then tell application "Finder" to open (POSIX file targetMatch) as alias
end if