HowTo: grep All Sub-directory For Files

by on December 20, 2012 · 0 comments· LAST UPDATED November 20, 2013

in , ,

How do I grep all sub directories? How can I use grep command through all sub-directories on Linux or Unix like operating systems? How do I use grep to find pattern including all subdirectories on OS X/BSD/Unix-like operating systems?

grep command is used to search files. The basic syntax is:

Tutorial details
DifficultyEasy (rss)
Root privilegesNo
Requirementsgrep+Terminal
Estimated completion time1m
grep 'word' file
grep 'word1 word2' file1 file2
grep [option] 'word1 word2' file1 file2

You can search all text files in the current directory with wild cards:

grep 'word-to-search' *

Search sub directories recursively using grep

Pass the -r option to grep command to search recursively through an entire directory tree. With this option one can search the current directory and and all levels of subdirectories by passing the -r or -R to the grep command. The syntax is:

 
grep -r 'word-to-search' *
 

OR

 
grep -R 'word-to-search' *
 

Examples

For example, the following would search all files in the current directory and in all of its subdirectories for every line containing the word 'main()':

 
grep -r 'main()' *
 

The following example would search for /etc/ and all of its subdirectories for every line containing the ip address '192.168.1.254':

 
grep -r '192.168.1.254' /etc/
 
Recommend readings
TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 0 comments… add one now }

Leave a Comment

Tagged as: ,

Previous Faq:

Next Faq: