As a Linux user you’ll inevitable need to search around for a specific file once in a while, be it a configuration file you need to edit or a version of a document you somehow lost.
There are three basic ways to search for files using the command line:
The locate command is the fastest and simplest way to search for files. You just need to type:
and you’ll get a list of files that contain the specified string somewhere in their path. Careful therefore to not use strings that appear as directory names, like usr or doc.
Another caveat: locate searches for files in the system database, which is only updated once a day. In other words, you might not be able to find recently added files (and some files never go to the database).
The specified string can be a regex pattern, and you can also add some options to the search. For instance, -i will make the search case insensitive, and -c will only count the display the number of matches found. Type “man locate” to see all the options.
The find command is slower than the locate one because it searches the live filesystem. That being said it’s much more powerful.
find /home -name string
Keep in mind that if you don’t specify a directory, find will start looking at the current directory and into deeper ones.
Second, notice that you need to specify the ‘name’ attribute, cause name is only one of the attributes you can use to search for files with this command.
Other commonly used attributes are:
Grep is useful when you need to find files that contain a specific text pattern inside them. Its use is a little more complicated. The basic way to run it is:
grep options pattern file
Some useful options:
-i make the search case insensitive
-v invert the sense of matching
-n display the number of the matching line
If you want to search all files in the current directory and on subdirectories you can use this:
grep -r pattern .