How to Find Files Containing Specific Text in Ubuntu (find & grep)

The Content Search

The standard Linux find command is incredibly powerful for locating files based on metadata like filename, size, or date. However, the find engine cannot look inside a file to read its contents. If you need to search an entire web directory to locate exactly which PHP file contains a specific database password or a specific line of code, you must combine the power of find with the text-searching capabilities of the grep command.

Combining find and grep with -exec

You can use the -exec flag to force the find command to pass every single file it discovers directly into the grep engine for text analysis.

  1. Open your Terminal application (Ctrl + Alt + T) or log into your server via SSH.
  2. To scan the entire /var/www/html/ directory for any file containing the exact text string “DB_PASSWORD”, type the following command exactly:
    sudo find /var/www/html/ -type f -exec grep -l "DB_PASSWORD" {} +
  3. Press Enter and provide your administrator password.

Command Breakdown

The command first finds every single regular file (-type f) in the directory. The -exec argument then takes those files (represented by the {} placeholder) and feeds them to grep. The -l (lowercase L) flag is absolutely crucial: it tells grep to only print the name of the file containing the text, rather than dumping the entire contents of the file onto your screen. The + at the end of the command tells find to group the files together before sending them to grep, which makes the search significantly faster than using the standard \; terminator.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.