How do I search string recursively in the file system with grep command? Linux grep command is a frequently used command by most of the Linux users. Using grep you can search any string in all files available in the directory hierarchy. You will get come examples of grep command to search any string recursively in the file system.
Syntax:
Grep command uses following syntax to search pattern Recursively in all files available under specific directory and its sub directories.
grep -R "search-pattern" /path/to/search/dir
Search Pattern Recursively in Files
For example, you want to search a string “Hello” in all files available under /var/www
directory. Also search the files under subdirectories of parent directory.
grep -R "Hello" /var/www
This will traverse the directory tree under /var/www and print all files including line content containing string “Hello”.
The above command will search for case sensitive string only. You can also search for strings matching in any case.
grep -R "Hello" /var/www
This will all string in any case like “hello”, “HELLO” or HeLLo” etc.
Search Pattern Recursively in Specific Extension Files:
Make your search more specific, like search a string “example.com” in all files with the extension .php only. To achieve this use --include
option to force grep to search for the specific file only and ignore others.
grep -R --include="*.php" "Hello" /var/www
You may also specify multiple file extensions to search
grep -R --include="*.php" --include="*.conf" "Hello" /var/www
Conclusion
In this tutorial, you have learned to search a string in all files under a directory tree on Linux.