Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to perform grep operation on all files in a directory?
The grep command in Linux is used to search for patterns within files. It displays lines that match a specified pattern (regular expression) and is one of the most essential utilities for text processing and file searching in Linux systems.
Basic Syntax
grep [options] pattern [files]
Common Options
| Option | Description |
|---|---|
-c |
Lists only a count of matching lines |
-h |
Displays matched lines without filenames |
-i |
Ignores case for matching |
-l |
Prints filenames only (not the matching lines) |
-n |
Displays matched lines with line numbers |
-r |
Searches recursively through subdirectories |
-v |
Prints lines that do NOT match the pattern |
Searching All Files in a Directory
Recursive Search (Including Subdirectories)
To search for a pattern in all files within a directory and its subdirectories, use the -r (recursive) option −
grep -rni "pattern" *
This command combines three useful options −
-r− Search recursively through subdirectories-n− Show line numbers-i− Ignore case sensitivity
Example − Finding a Function
grep -rni "func main()" *
main.go:120:func main() {}
utils/helper.go:45:func main() {
Search Current Directory Only
To search only in the current directory without descending into subdirectories, use the -s option to suppress error messages −
grep -s "pattern" *
Example − Current Directory Search
grep -s "func main()" *
main.go:120:func main() {}
Using Find Command with Grep
For more complex searches, combine the find command with grep to search specific file types −
find . -name "*.go" -exec grep -H "func main" {} \;
This command −
find . -name "*.go"− Finds all .go files in current directory and subdirectories-exec grep -H "func main" {} \;− Executes grep on each found file-H− Forces filename display even for single files
./main.go:func main() {
./cmd/server/main.go:func main() {
Additional Techniques
Search with File Type Filtering
grep -r --include="*.txt" "pattern" .
Exclude Certain Directories
grep -r --exclude-dir=node_modules "pattern" .
Conclusion
Grep operations on directories are essential for code analysis and file management. Use grep -rni for comprehensive recursive searches, or combine find with grep for more targeted searches with specific file types and exclusion patterns.
