To find all files containing a specific text string on Linux, use the grep
command with appropriate options. Here are the most common methods:
1. Basic Search (Case-Sensitive)
Search for a string in all files under a directory (recursive):
grep -r "search_text" /path/to/directory
2. Case-Insensitive Search
Add the -i
flag to ignore case:
grep -ri "search_text" /path/to/directory
3. List Only Filenames (No Match Text)
Use -l
to show files that contain the text:
grep -rl "search_text" /path/to/directory
4. Exclude Binary Files
Skip binary files (e.g., images, executables) with -I
:
grep -rI "search_text" /path/to/directory
5. Search for Whole Words Only
Match exact words (not substrings) with -w
:
grep -rw "search_text" /path/to/directory
6. Use Regular Expressions
Enable extended regex with -E
(e.g., patterns like error|warning
):
grep -rE "error|warning" /path/to/directory
Examples
- Search for “hello world” in the current directory (case-insensitive):
grep -ri "hello world" .
- Find files containing “localhost” in
/etc
(filenames only):
grep -rl "localhost" /etc
- Search for the exact word “error” in log files:
grep -rw "error" /var/log
Alternative Tools
ripgrep
(rg): Faster and modern alternative togrep
.
rg "search_text" /path/to/directory
ack
: Designed for code searches (ignores binaries by default).
ack "search_text" /path/to/directory
Key Options
Option | Description |
---|---|
-r | Search recursively in directories. |
-i | Case-insensitive search. |
-l | List filenames only (no match text). |
-I | Ignore binary files. |
-w | Match whole words only. |
-n | Show line numbers of matches. |
By combining these options, you can efficiently locate text in files on Linux!