Is there a way to ask mdfind to search for filenames with an exact filename ?

At some point in a pipe I have this:

(filenames are produced here) | while read f; do mdfind -name "$f" | grep -E "/$f";

I have two problems:

  • if the filename contains a +:

    grep: repetition-operator operand invalid

  • if the filename contains a parenthesis, the result is empty.

How can I fix this ?


I think that you don't need any regular expressions here. Just try to search for a fixed string with grep. You can enable fixed string matching with the -F switch.

Given that your command line looks like

(filenames are produced here) | \
while read f ; \
    do mdfind -name "$f" | grep -F "/$f" ; \

Use the power of the man page. ;)

The man page of mdfind says:

 -literal    Force the provided query string to be taken as a literal query string, without interpretation.

Without that option mdfind interprets characters like "*", "+" and "()" as regular expression.

The metadata attribute for file name is kMDItemFSName. So, to find a file with a specific name:

mdfind -literal 'kMDItemFSName = "somefile.txt"'

Bonus tip: You can also use mdls /path/to/somefile.txt to inspect the file's metadata

  • But is the filename a metadata attribute ? – alecail Jan 22 '13 at 11:59
  • This works:mdfind -literal 'kMDItemFSName == .. but it is so slow that it is not usable. mdfind -name returns almost immediately, -literal takes easily 30 seconds on the request I tried. – alecail Jan 22 '13 at 12:11
  • @Antoine, that is weird. It should be faster not to have to consider alternatives. – vonbrand Jan 22 '13 at 14:48
  • @vonbrand I'll have a look later - I'm currently moving a few TB of files - it may be related – alecail Jan 22 '13 at 14:52
  • @vonbrand I just tested on a non busy system and it's incredibly slow compared to mdfind -name. – alecail Jan 25 '13 at 11:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.