I'm a newly minted CS major and I have been wondering what the benefits of using grep versus spotlight on mac. I ran a command to search for a specific file because I lost track of which directory it is in, which took a while, but when I did it in spotlight the result was instantaneous. I enjoy using the command line and it makes my life much simpler than the UI directory view on mac, so I would like to learn how to use it to its full potential.
grep is usually to search file contents for matching patterns. Think searching file contents.
grep will have to manually walk the file system from a given starting point.
I am curious how you were using
find is the standard *nix command to search your file system for a file. Check out the man page, it has lots of ways to use it. But basically, it walks your file system from a given starting point and looks for matches.
spotlight is an OSX utility that searches an indexed list of files.
spotlight relies on an index and thus is capable of very fast lookups as it is not manually iterating over the file system. Usually a worker thread does that to build the index.
The tradeoff with spotlight is that if the file has not been indexed, then spotlight will not find it, even if it exists. However, if the directory has been indexed, then spotlight has good performance.
If you are needing to search for file contents and are using version control, say on a development project,
ag silver_searcher is a much faster alternative to
grep. It works within version control scenarios and respects your list of ignored file types to find files containing a pattern
As a possible solution for you; OS X also has a
locate command that utilizes indexing to find files. That is probably your best bet of seeing the same search performance on the cli that you see in spotlight. In order to setup your database you must run the command:
sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.locate.plist
Once your database has been created you can use: