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?
Best Answer
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 usefind
to output only file pathnames using the-type t
option, wheret
is set tof
for regular file.Example:
Where
'search'
is whatever you'regrep
ing for, and the output will be the relative path filename of the file(s) containing it because of using-l
withgrep
.In the example above,
grep
will be executed for each relative path filename thatfind
passes to-exec
. Asgrep
can handle multiple filenames, you can change the;
, at the end of the command, to+
to tellfind
to pass all the matching filenames togrep
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 passedgrep
, depending on your needs.