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 grep a string in a directory and all its subdirectories in Linux?
The grep command in Linux is used to search for specific patterns or strings within files. It is one of the most essential Linux utilities for filtering and finding text content across files and directories.
The pattern we search for is typically called a regular expression, and grep can search through single files, multiple files, or entire directory structures.
Basic Syntax
grep [options] pattern [files]
Common Options
| Option | Description |
|---|---|
-r or -R
|
Search recursively through directories and subdirectories |
-n |
Display line numbers with matched lines |
-i |
Ignore case sensitivity when matching |
-l |
Print only filenames that contain matches |
-h |
Display matched lines without filenames |
-c |
Count the number of matching lines |
-v |
Show lines that do NOT match the pattern |
Searching in Directory and All Subdirectories
To search for a string in all files within a directory and its subdirectories recursively, use the following syntax −
grep -rni "search_string" /path/to/directory
For the current directory, you can use a wildcard −
grep -rni "search_string" *
Example − Search for Function Declaration
grep -rni "func main()" *
main.go:120:func main() {}
utils/helper.go:45:func main() {
src/app.go:8:func main() {
This command searches for the string func main() in all files within the current directory and subdirectories, showing filenames, line numbers, and ignoring case.
Searching Only in Current Directory
To search only in the current directory without going into subdirectories, use the -s flag to suppress warnings about subdirectories −
grep -s "func main()" *
main.go:120:func main() {}
Using find Command with grep
An alternative approach combines the find command with grep for more precise control over which files to search −
find . -name "*.go" -exec grep -H "func main" {} \;
./main.go:func main() {
./utils/helper.go:func main() {
This command finds all .go files in the current directory and subdirectories, then searches for func main in each file.
Advanced Examples
Search with File Type Filtering
grep -r --include="*.txt" "error" /var/log/
Exclude Specific Directories
grep -r --exclude-dir="node_modules" "function" ./
Count Matches Across All Files
grep -rc "TODO" .
Conclusion
The grep command with the -r option is the most efficient way to search for strings across entire directory structures in Linux. Combined with options like -n, -i, and file filtering, it provides powerful text searching capabilities for system administration and development tasks.
