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
- Fix “sudo command not found”
- Install a Specific Version with apt-get on Ubuntu/Debian
- Fix Ubuntu/Debian apt-get “KEYEXPIRED: The following signatures were invalid”
- How to Test a Cron Job
- How to Unzip Into a Folder
- How to Show Your Elasticsearch Version on Ubuntu/Debian
- Use “which” in Linux to find the Location of an Exetable
- Sort “ls” by Last Changed Date
- How to Shutdown a Machine
- Show Hidden Files and Folders with `ls`
- Case Insensitive Search
- Search Recursive in Subdirectories
- Search all Files in a Directory (Non-Recursively)
- Search in Multiple Log Files
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!