HowTo: Use Grep Command In Unix / Linux To Search Subdirectories

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:

Tutorial details
Difficulty level Easy
Root privileges No
Requirements grep
Est. reading time N/A

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:

Fig.01: grep in action


🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 5 comments so far... add one


CategoryList of Unix and Linux commands
Disk space analyzersdf duf ncdu pydf
File Managementcat cp mkdir tree
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Modern utilitiesbat exa
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg glances gtop jobs killall kill pidof pstree pwdx time vtop
Searchingag grep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
5 comments… add one
  • Jalal Hajigholamali Oct 20, 2012 @ 12:48

    Hi,

    Thanks for this article

  • M.S. Babaeu Oct 20, 2012 @ 21:15

    That’s great !!
    I always did
    # find /path/to/search | xargs grep ‘main()’
    with your method you have more control over the output.

  • Babur Oct 22, 2012 @ 3:45

    Great article!

  • Steve Klabnik Oct 22, 2012 @ 6:02

    ack is better

  • lokesh Oct 25, 2012 @ 14:41

    good articel

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum