How To Use Grep Command Recursively Through Sub-Directories In Linux?

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/use-grep-command-recursively-sub-directories-linux/
PINTEREST
PINTEREST
INSTAGRAM

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.

Recursive -r Option
Recursive -r Option

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 --includeoption.

Specify File Name Pattern or Extension
Specify File Name Pattern or Extension

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.

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.

LEARN MORE  Python Regular Expression Operations - Regex

Search Case-Insensitive
Search Case-Insensitive

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.

Search Multiple Directories
Search Multiple Directories

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/use-grep-command-recursively-sub-directories-linux/
PINTEREST
PINTEREST
INSTAGRAM