grep
is very useful command to search files and directories. What makes grep
powerful is that it can search file contents. We can search file content according to extension. Recursive behavior makes it more powerful by looking sub directories and files.
Introduction to Linux Grep Command With Examples
Recursive -r Option
We will start with a simple example and only specifying recursive option -r
which is shortcut for “recursive”. In this example we will search files those have string import
. We will search /home
directory.
$ grep -r "import" /home/

Specify File Name Pattern or Extension
We can specify file pattern to search recursively. For example if we want to search the Python script or code files content we can use *.py
file pattern to look only those files recursively. In this example we will search for import
term. We will use --include
option.
$ grep -r --include "*.py" "python3" /home/

Exclude Specified File Name Pattern or Extension
We can also specify the file name patterns or extensions we want to exclude. For example if we only want to search python scripts but not pyc
or python cache files we can specify to exclude pyc
. We will use --exclude
option for this.
$ grep -r --exclude "*.pyc" "python3" /home/
Search Case-Insensitive
By default grep
will search case sensitive. Case sensitive will look exact term. If we want to look incase-sensitive we should provide -i
option. In this example we will search test
case-insensitive which means alternative like TEST
Test
etc. will be looked for.
$ grep -r -i "test" /home/

Search Multiple Directories
In previous examples we have provide only single directory to search. In some cases we may need to search multiple directories those resides in different path. In this example we will search directories /etc
/usr/shareand
/home` in single command by adding them to the end of the command.
$ grep -r -i "test" /etc/ /usr/share/ /home/
