grep — Search all Files in a Directory (Non-Recursively)

grep is a powerful tool for searching for a pattern in files. You can search in a single file, all directory files, or recursively through all files in a directory.

A use case to search through all files in a directory is finding information in application log files. You may want to retrieve more context information about a request and that could involve multiple files. This tutorial shows you how to search non-recursively through all files in a directory.

Ubuntu/Debian Series Overview

Search Non-Recursively all Files in a Directory with grep

You may provide a file or directory path to grep and it starts its search. A thing to keep in mind is that grep expects a file path by default. When passing a directory path to grep it will tell you that the path is a directory and you need to be more specific on what to search for:

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

Grepping all Files in a Directory

Use glob patterns in the directory path to tell grep to search all files in a given directory. A glob pattern representing all files in a directory is the *.

Here’s a code snippet showing you how to search for a pattern in the current directory:

# search through all files in the current directory
grep "pattern" *  

You may also search in a nested directory and append the * to the path provided to grep:

# search through all log files
grep "pattern" storage/logs/*  

That’s it!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.