I would like to search and find all files which contain a word called "main()" for all directories located in $HOME/project/school. How do I use the grep command to find text including all subdirs under Unix or Linux operating systems?
The grep command is used to search text for patterns (words) specified on the command line. You need to use the following syntax:
grep -r 'word' /path/to/dir
The -r option is used to search recursively through an entire directory tree. For example, the following would search all files in the current directory and in all of its subdirectories including their subdirectories for every line containing the word "main()":
grep -r 'main()' ~/projects/school
You can also display the name of each file from which output would normally have been printed with the -l option:
grep -rl 'main()' ~/projects/school
You can print the file name for each match with -H option:
grep -rH 'main()' ~/projects/school
Finally, you can display line number too with the -n option:
grep -rHn 'main()' ~/projects/school
The -i option instructs grep to ignore case. Thus, for instance, the the following example could very easily be converted to a case-insensitive search as follows (match main(), MAIN(), mAiN() and so on):
grep -rHni 'main()' ~/projects/school
In this example, search for an IP address 192.168.1.5:
grep -Hrn --color '\<192.168.1.5\>' /etc
Sample outputs:
- 30 Handy Bash Shell Aliases For Linux / Unix / Mac OS X
- Top 30 Nmap Command Examples For Sys/Network Admins
- 25 PHP Security Best Practices For Sys Admins
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- Linux: 20 Iptables Examples For New SysAdmins
- Top 20 OpenSSH Server Best Security Practices
- Top 20 Nginx WebServer Best Security Practices
- 20 Examples: Make Sure Unix / Linux Configuration Files Are Free From Syntax Errors
- 15 Greatest Open Source Terminal Applications Of 2012

- My 10 UNIX Command Line Mistakes
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- The Novice Guide To Buying A Linux Laptop





![Linux Copy File Command [ cp Command Examples ]](http://s0.cyberciti.org/images/rp/1/26.jpg)






{ 5 comments… read them below or add one }
Hi,
Thanks for this article
That’s great !!
I always did
# find /path/to/search | xargs grep ‘main()’
with your method you have more control over the output.
Great article!
ack is better
good articel