Logo

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

You can use the grep command to search recursively for all files containing a specific text. Here’s the basic syntax:

grep -r "search_string" /path/to/directory

Below are some useful flags and variations:

  1. Basic Recursive Search

    grep -r "Hello World" .
    • -r: Recursively searches all subdirectories in the current directory (.).
    • Prints matches with the filename and the matching line.
  2. Showing Line Numbers

    grep -rn "Hello World" .
    • -n: Displays the matching line number in addition to the filename.
  3. Case-Insensitive Search

    grep -ri "hello world" .
    • -i: Ignores case differences (matches “HELLO”, “Hello”, etc.).
  4. Match Whole Words

    grep -rw "hello" .
    • -w: Matches only whole words, not partial matches (so “hello” is matched, but “helloworld” is not).
  5. Filtering by Filename or Extension

    grep -r --include="*.txt" "search_string" .
    • --include="*.txt": Searches only in files matching the specified pattern (e.g., “*.txt”).
  6. Excluding Certain Files or Directories

    grep -r --exclude="*.log" --exclude-dir="node_modules" "search_string" .
    • --exclude="*.log": Skip files ending with “.log”.
    • --exclude-dir="node_modules": Skip the “node_modules” directory.
  7. Using find and grep Together

    find /path/to/directory -type f -exec grep -H "search_string" {} \;
    • -type f: Finds only regular files (no directories).
    • -exec ... {} \;: Executes grep on each file found.
    • -H: Ensures the filename is printed with matches.
  8. Alternatives

    • ack, the_silver_searcher (ag), or ripgrep (rg) are popular third-party tools offering faster or more flexible searches. For example:
      rg "search_string"
      By default, ripgrep (rg) is recursive, ignores binary files, and respects .gitignore.

Quick Reference: Common grep Flags

  • -r / -R: Recursive search in subdirectories.
  • -n: Show line numbers.
  • -i: Case-insensitive match.
  • -w: Match whole words only.
  • -v: Invert match (show lines that do not match).
  • --include / --exclude: Filter files by name pattern.
  • --exclude-dir: Filter entire directories.
  • -H: Print filename even if only one file is matched.

That’s all you need to know to locate every file containing a specific string on a Linux system using grep. Adjust the flags as needed to refine your search, and consider advanced tools like ripgrep or ack if you need faster or more specialized functionality.

Recommended Resources

CONTRIBUTOR
TechGrind