grep — Search Recursive in Subdirectories

grep allows you to search for a pattern in a file’s content. This tool searches even through large files, like application logs. You may also search recursively for a pattern in files of a directory and related subdirectories.

This tutorial shows you how to run a recursive search on all files in a directory.

Ubuntu/Debian Series Overview

Search Recursively in Subdirectories with grep

You can’t pass a directory path to grep. You’ll see an error message that your given path is a directory:

$ grep "hostname" storage/logs
grep: data/logs: Is a directory  

grep expects a file path by default. A directory path requires you to add specific options. For example, grep supports a --recursive flag to search through all files within the storage/logs directory:

grep --recursive "pattern" storage/logs

# use the "-r" shorthand for "--recursive"
grep -r "pattern" storage/logs  

The --recursive flag tells grep to take the path argument and treat it as a directory and the starting point for the search through all files within the directory itself or any subdirectory. Any match for the search pattern has the file name as a prefix in the output:

$ grep --recursive "hostname" storage/logs
storage/logs/default.log:{"hostname":"55ec743122e6", …}  
storage/logs/cms.log:{"hostname":"55ec743122e6", …}  
storage/logs/cli/default.log:{"hostname":"68ab13594b24", …}  
storage/logs/cli/delete-audit.log:{"hostname":"68ab13594b24", …}  

That’s it!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.