Trouble with mdfind

I’ve got a problem using mdfind to find files matching more than one attribute. I want my applescript to find files whose filenames end with a .txt extension, whose content contains a certain phrase, and which have an index label of 7 (gray).

Pretty simple right? But I must be doing something wrong because any time I try to search for more than one of these at a time, I get an error message.


set downloads to "Macintosh HD:Users:des:Downloads:"
set desktoppath to quoted form of POSIX path of (downloads)
set spotlightquery to "\"kMDItemFSName == '*.txt'\" && kMDItemTextContent == \"the phrase\""
set command to "mdfind -onlyin " & desktoppath & " " & spotlightquery
set founditems to paragraphs of (do shell script command)

The error I get here is: error “sh: kMDItemTextContent: command not found” number 127

What am I doing wrong? Thanks much.

Hi. Shell commands aren’t really my strong suit, but I think that multiple search parameters that are strung together need to be quoted as a unit. Try:


do shell script ("mdfind -onlyin " & "~/Downloads " & (("kMDItemFSName == " & ("*.txt")) & " && " & ("kMDItemTextContent == " & ("the phrase")'s quoted form))'s quoted form)'s paragraphs

–edited to include a second quoted form for the text content, which makes the search contiguous

I guess

mdfind -onlyin ‘/Macintosh HD/Users/des/Downloads/’ “kMDItemFSName == ‘*.txt’” && kMDItemTextContent == “the phrase”

is not what you wanted.

I’ll have to agree with you, mouramartins. :slight_smile: I prefer the parenthetical setoffs, to see the logical breaks in the commands and to allow the flexibility of further altering the search terms with an additional possessive; I have a hard time seeing an apostrophe that’s adjacent to a quote. This is to what my code evaluates without the parentheses:

“mdfind -onlyin ~/Desktop/ ‘kMDItemFSName == *.txt && kMDItemTextContent == the phrase’”