How to Find Files Using Regex Patterns in Ubuntu (find -regex)

The Limitations of Wildcards

When searching for files in Ubuntu Linux, the standard -name flag allows you to use basic wildcards (like *.txt). However, wildcards are often too simple for complex audits. If you need to find log files that start with “error,” followed by exactly four digits, and ending in either “.log” or “.bak”, a simple wildcard cannot handle the logic. To perform highly complex, granular searches based on specific naming structures, you must instruct the Linux engine to process the search string as a full Regular Expression (Regex).

Using the find Command with -regex

The Linux find command utilizes the -regex flag to evaluate file paths against complex regular expression patterns.

  1. Open your Terminal application (Ctrl + Alt + T) or log into your server via SSH.
  2. To scan the /var/log/ directory for files matching a specific pattern, type the following command exactly:
  3. find /var/log/ -type f -regex ".*error[0-9]\{4\}\.\(log\|bak\)"
  4. Press Enter.

Crucial Regex Path Rules

Unlike the -name flag, which only looks at the exact filename (e.g., file.txt), the -regex flag evaluates the entire absolute file path returned by the search engine (e.g., /var/log/file.txt). This means your regular expression must account for the leading directories. This is why the example command above starts with .* (meaning “match any character leading up to the word error”). If you simply run -regex "error.*", it will fail, because the string being evaluated actually starts with /var/.

Get the best tech tips delivered straight to your inbox.

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