grep is a powerful tool on Linux and UNIX-based operating systems. It searches for patterns in files and is flexible enough to search through multiple files. You may select a set of files manually or use a glob pattern to find the files to grep on.
This tutorial shows you how to search a pattern in multiple files using grep.
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 in Selected Files
Search in Selected Files with grep
You can select specific files and pass them as arguments to grep when searching for patterns. The selected files can be of different file types. You may combine a log file and a language-specific file, like the package.json
:
grep "pattern" storage/logs/app.log package.json
Search in a Specific Type of Files with grep
You may not know all the files in a directory and need a dynamic approach to select the files in which you want to search for the keyword. Use a glob pattern with grep to let the tool find all files matching the pattern.
grep "pattern" storage/logs/*.log
The output will have the file name as a prefix of the matching line. Everything after the file name is the matching content found in the related file.
Here’s a preview of how the results will look like:
$ grep "pattern" storage/logs/*.log
storage/logs/app.log:{"hostname":"55ec743122e6", …}
storage/logs/cms.log:{"hostname":"12ab554433f7", …}
Search Recursively in Files of a Given Type with grep
You may add flags to grep when searching through files. For example, if you want to recursively find matches in your JavaScript files use the --recursive
flag and a glob pattern for the file path.
Here’s a sample call for that:
grep -r "pattern" src/**/*.js
Here’s a preview of how the results are printed. Notice that the output contains the line’s indention as well as comments.
src/utils/index.js: // you may use a different pattern here
src/database/driver.js: console.log('the b-tree pattern works nicely')
That’s it!