How to find all files containing a specific text (string) on Linux?

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

  1. Search for “hello world” in the current directory (case-insensitive):
   grep -ri "hello world" .
  1. Find files containing “localhost” in /etc (filenames only):
   grep -rl "localhost" /etc
  1. Search for the exact word “error” in log files:
   grep -rw "error" /var/log

Alternative Tools

  • ripgrep (rg): Faster and modern alternative to grep.
  rg "search_text" /path/to/directory
  • ack: Designed for code searches (ignores binaries by default).
  ack "search_text" /path/to/directory

Key Options

OptionDescription
-rSearch recursively in directories.
-iCase-insensitive search.
-lList filenames only (no match text).
-IIgnore binary files.
-wMatch whole words only.
-nShow line numbers of matches.

By combining these options, you can efficiently locate text in files on Linux!

Leave a Reply

Your email address will not be published. Required fields are marked *