Post

find string recursively with grep

Sometimes all you want to do is find what file contains that text string your looking for.

1
grep -rl "string" /path

flags

-r (or –recursive)

option is used to traverse also all sub-directories of /path, whereas

-l (or –files-with-matches)

option is used to only print filenames of matching files, and not the matching lines (this could also improve the speed, given that grep stop reading a file at first match with this option).

grep is a powerful command-line utility in Unix-like operating systems used for searching text patterns within files. The name “grep” stands for “Global Regular Expression Print.” It allows you to search for a specific string or regular expression in one or multiple files.

Here’s a basic example of how you can use grep to find a string of text within a collection of files:

  1. Open your terminal.

  2. Navigate to the directory where your files are located using the cd command. For example:

    1
    
     cd path/to/your/files
    
  3. Use the grep command with the -r (or -R) option for a recursive search, and provide the string you want to search for followed by the file or directory names:

    1
    
     grep -r "your_string" .
    
    • -r or -R: Recursively search subdirectories.
    • "your_string": Replace this with the actual string you want to find.
    • .: Represents the current directory. You can replace this with a specific file or directory name.
  4. grep will then display lines containing the specified string along with the filenames where the matches are found.

For example, if you want to find the string “example” in all text files within the current directory and its subdirectories, you would run:

1
grep -r "example" *.txt

This command recursively searches for “example” in all text files (*.txt) and outputs the matching lines along with the file names.

This post is licensed under CC BY 4.0 by the author.

Comments powered by Disqus.