How to search filenames by regex with "find"

BashUnix

Bash Problem Overview


I was trying to find all files dated and all files 3 days or more ago.

find /home/test -name 'test.log.\d{4}-d{2}-d{2}.zip' -mtime 3

It is not listing anything. What is wrong with it?

Bash Solutions


Solution 1 - Bash

find /home/test -regextype posix-extended -regex '^.*test\.log\.[0-9]{4}-[0-9]{2}-[0-9]{2}\.zip' -mtime +3
  1. -name uses globular expressions, aka wildcards. What you want is -regex
  2. To use intervals as you intend, you need to tell find to use Extended Regular Expressions via the -regextype posix-extended flag
  3. You need to escape out the periods because in regex a period has the special meaning of any single character. What you want is a literal period denoted by \.
  4. To match only those files that are greater than 3 days old, you need to prefix your number with a + as in -mtime +3.
Proof of Concept
$ find . -regextype posix-extended -regex '^.*test\.log\.[0-9]{4}-[0-9]{2}-[0-9]{2}\.zip'
./test.log.1234-12-12.zip

Solution 2 - Bash

Use -regex not -name, and be aware that the regex matches against what find would print, e.g. "/home/test/test.log" not "test.log"

Solution 3 - Bash

Start with:

find . -name '*.log.*.zip' -a -mtime +1

You may not need a regex, try:

 find . -name '*.log.*-*-*.zip' -a -mtime +1

You will want the +1 in order to match 1, 2, 3 ...

Solution 4 - Bash

Use -regex:

From the man page:

-regex pattern
       File name matches regular expression pattern.  This is a match on the whole path, not a search.  For example, to match a file named './fubar3',  you  can  use  the
       regular expression '.*bar.' or '.*b.*3', but not 'b.*r3'.

Also, I don't believe find supports regex extensions such as \d. You need to use [0-9].

find . -regex '.*test\.log\.[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]\.zip'

Solution 5 - Bash

Just little elaboration of regex for search a directory and file

Find a directroy with name like book

find . -name "*book*" -type d

Find a file with name like book word

find . -name "*book*" -type f

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTreeView Question on Stackoverflow
Solution 1 - BashSiegeXView Answer on Stackoverflow
Solution 2 - BashErikView Answer on Stackoverflow
Solution 3 - BashDigitalRossView Answer on Stackoverflow
Solution 4 - BashdogbaneView Answer on Stackoverflow
Solution 5 - BashHafiz Muhammad ShafiqView Answer on Stackoverflow