How to Recursively Search all Files for Strings on a Linux

The grep command is used to search text and scan files for lines containing a match to given strings or words. It searches for lines that match regular expressions and outputs only the matching lines. Using grep with the recursive option, we can search through all files in a directory and its subdirectories for specific strings on Linux.

Basic Recursive Search Syntax

The basic syntax for recursive searching is:

$ grep -r "search_term" /path/to/directory

If no directory is specified, grep searches the current directory:

$ grep -r "search_term"

Examples

Searching for a Specific Word

To search for the word "Linux" in the Downloads directory:

~/Downloads$ grep -r "Linux"

Sample output:

zookeeper_installation.htm:<li><p><b>Any of Linux OS</b> ? Supports development and deployment.</p></li>
Linux Howtos.html:1. How to add a New Disk Drive to a Linux System?
Linux Howtos.html:2. How to create a new virtual disk for an existing Linux virtual machine?
Linux Howtos.html:4. How to Increase the size of a Linux LVM by adding a new disk
Linux Howtos.html:5. How to format a Linux Hard Disk?
Linux Howtos.html:6. How to partition and format a new drive in Linux System?
Linux Howtos.html:7. How to mount NTFS Drives on a Linux System?

Case-Insensitive Search

To ignore case distinctions and match both uppercase and lowercase variations:

$ grep -ri "linux" .

Sample output:

zookeeper_installation.htm:<li><p><b>Any of Linux OS</b> ? Supports development and deployment.</p></li>
zookeeper_installation.htm:The latest version is JDK 8u 60 and the file is "jdk-8u60-linux-x64.tar.gz".
zookeeper_installation.htm:$ tar -zxf jdk-8u60-linux-x64.gz

Display Only Filenames

To display only the names of files containing matches (without showing the actual matching lines):

$ grep -r -l "linux"

You can also search in specific file types within a directory:

$ grep -r -l "linux" /path/to/dir/*.c

Common grep Options for Recursive Search

Option Description
-r Recursive search through directories
-i Ignore case (case-insensitive search)
-l Show only filenames containing matches
-n Show line numbers with matches
-H Show filename with each match

Advanced Examples

Search with line numbers:

$ grep -rn "error" /var/log/

Search for exact word matches only:

$ grep -rw "function" /home/user/code/

Search excluding certain file types:

$ grep -r --exclude="*.log" "config" /etc/

Conclusion

The grep command with the recursive option (-r) provides a powerful way to search through all files in a directory structure. Combined with options like case-insensitive search (-i) and filename-only output (-l), it becomes an essential tool for efficiently locating text patterns across multiple files in Linux systems.

Updated on: 2026-03-17T09:01:38+05:30

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements