Yesterday's post detailed how you can find files by their name, permissions, time, or other descriptors. But you probably also want to be able to find files based on what is inside them. Grep is a tool that picks up where find left off, and can search inside files (though cannot do the same things that find can).
Again, we'll start with the syntax of the command:
grep pattern files
- grep is the command to start the search. Other options are available here, described below.
- pattern is a basic regular expression to search for in the files.
- files is a file or folder (or set of files) that you want to search.
The -r option for grep makes it search recursively in a directory, so if you are searching in a folder, be sure to use it. Another option is to use the command rgrep instead of grep, which automatically applies the recursive command.
Another common option is -i, which makes searches case-insensitive.
Yet another option is for advanced regular expressions: -E or command egrep to use some extended (Perl-type) expressions.
Those in mind, let's try an example:
egrep -i -r 'fosswire\.(com|net)' /home
- egrep is the same as grep -E, which tells grep to use extended Perl expressions.
- -i ignores any capitalization.
- -r searches recursively, since this is a directory search.
- 'fosswire\.(com|net)' will match either fosswire.com or fosswire.net. This is a regular expression, the syntax is beyond the scope of this tutorial. If you just want to search for a string, just use regular grep.
- /home specifies the directory we want to start in.
Another method of searching with grep is by using a something called stdin. To use it, just run another program before grep and seperate them with a pipe (|) character.
For example, a common command is to search for the word "direct" in the glxinfo command:
glxinfo | grep direct
Note that I skipped the last files part of the grep command. This is because it is reading directly from glxinfo. When run, the above command will output something similar to:
direct rendering: Yes
You should now have all of the tools needed to effectively search through and maintain your files through a command-line interface. Grep away.