0
0
Linux-cliHow-ToBeginner · 3 min read

How to Use grep Recursively to Search Files in Linux

Use grep -r 'pattern' /path/to/directory to search recursively inside all files under the directory. The -r option tells grep to look into all subdirectories and files.
📐

Syntax

The basic syntax for recursive search with grep is:

  • grep -r 'pattern' /path/to/directory

Here:

  • -r means recursive search through all subdirectories.
  • 'pattern' is the text or regular expression you want to find.
  • /path/to/directory is where the search starts. You can use . for the current directory.
bash
grep -r 'pattern' /path/to/directory
💻

Example

This example searches for the word hello recursively in all files inside the current directory and its subdirectories.

bash
grep -r 'hello' .
Output
./file1.txt:hello world ./subdir/file2.txt:say hello to everyone
⚠️

Common Pitfalls

Some common mistakes when using recursive grep are:

  • Not using -r or -R, so only the current directory files are searched.
  • Using grep without quotes around the pattern, which can cause shell interpretation issues.
  • Searching binary files unintentionally, which can clutter output.

To avoid binary files, add --exclude-dir or use grep -r --exclude='*.bin'.

bash
grep 'hello' .
# Wrong: does not search subdirectories

grep -r hello .
# Better: recursive search with pattern unquoted (works but quoting is safer)

grep -r 'hello' .
# Best: recursive search with quoted pattern
📊

Quick Reference

OptionDescription
-rSearch recursively through directories
-RSame as -r, but follows symbolic links
--exclude='pattern'Exclude files matching pattern
--include='pattern'Include only files matching pattern
-iIgnore case when matching
-nShow line numbers in output

Key Takeaways

Use grep -r 'pattern' directory to search recursively in all files under a directory.
Always quote your search pattern to avoid shell issues.
Use --exclude or --include to filter files during recursive search.
Use -R if you want to follow symbolic links during recursion.
Add -n to see line numbers where matches occur.