How to Find Files Containing Specific Text in Ubuntu Linux

The configuration Needle in a Haystack

When you are managing an Ubuntu Linux server with thousands of configuration files spread across multiple directories, finding a specific setting can feel impossible. If your database server is throwing a memory error, you know you need to change the “max_connections” variable, but you have no idea which exact .conf file actually contains that text string. While the find command is excellent for locating files by their title, you need a different tool to rip through the filesystem, rip open every text file, and read the actual lines of code inside them.

Using the grep Command

The standard Linux grep command is the ultimate tool for searching the contents of files. By combining it with three specific flags, you can execute a massive, recursive text search.

  1. Open your Terminal application (Ctrl + Alt + T) or log into your server via SSH.
  2. Determine the parent directory you want to search. To search the entire /etc/ configuration folder, use that path.
  3. To search every single file inside that folder for the exact phrase “max_connections”, type the following command:
    sudo grep -rnw '/etc/' -e 'max_connections'
  4. Press Enter and provide your administrator password.

Understanding the Flags

This specific combination of flags (-rnw) is the holy grail for system administrators:

  • -r (recursive): This forces grep to look inside the main folder, then look inside every single sub-folder, and so on until it reaches the absolute bottom of the directory tree.
  • -n (line number): When grep finds the text, it will print exactly which line number it appears on (e.g., /etc/mysql/my.cnf:45: max_connections=100).
  • -w (whole word): This ensures it only finds the exact word. If you search for “net”, it won’t accidentally trigger on words like “network” or “internet”.
  • -e: This simply denotes the specific pattern you are searching for, allowing you to use spaces inside the quotation marks.

Get the best tech tips delivered straight to your inbox.

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