When searching with grep -r, it avoids following symbolic links by default. This is true for directories, but grep still inspects the contents of files that are symlinks.

For instance, if I have a framework with the following structure:

+-- MyFancy.framework
    +-- MyFancy              (symlink to ./Versions/A/MyFancy)
    +-- Versions
        +-- A
            +-- MyFancy      (the actual binary file)
        +-- Current
            +-- MyFancy      (symlink to ../A/MyFancy)

grep -r "string" MyFancy.framework prints:

Binary file ./MyFancy matches
Binary file ./Versions/A/MyFancy matches
Binary file ./Versions/Current/MyFancy matches

This causes the search in such structures three times slower.

How can I make grep exclude symlinks?

  • You can't. Use, e.g. find . -type f -exec grep -l 'search' {} \; where 'search' is whatever you're greping for. – user3439894 Jun 28 '17 at 11:10

If you look at the man page for grep, there is no option to exclude symlinks, and therefore an alternative method will need to be applied. One such method is to use find to output only file pathnames using the -type t option, where t is set to f for regular file.


 find . -type f -exec grep -l 'search' {} \; 

Where 'search' is whatever you're greping for, and the output will be the relative path filename of the file(s) containing it because of using -l with grep.

In the example above, grep will be executed for each relative path filename that find passes to
-exec. As grep can handle multiple filenames, you can change the ;, at the end of the command, to + to tell find to pass all the matching filenames to grep at once. Note that if the number of matching filenames is large, then the allowable length of the command line could be exceeded.

Also note that find has a rather large set of options, and as such you may be able to narrow down the output passed grep, depending on your needs.

  • Thanks! I did read the man, but thought -p is supposed to do what I'm looking for... just a few clarifications: 1. both + and ; seem to work the same, and grep prints the match immediately what am I missing? 2. Is there a difference between xargs and find -exec here? – Elist Jun 28 '17 at 18:12
  • @Elist 1. + will put multiple files as arguments to the same grep call for efficiency reasons. 2. If you use + then no there is not a practical difference. – 0942v8653 Jun 28 '17 at 22:18

You must log in to answer this question.

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