如何在文件查找中使用正则表达式

时间:2011-03-09 17:32:46

标签: bash unix

我试图在3天或更久之前找到所有过时的文件和所有文件。

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

它没有列出任何内容。这有什么问题?

5 个答案:

答案 0 :(得分:99)

find /home/test -regextype posix-extended -regex '^.*test\.log\.[0-9]{4}-[0-9]{2}-[0-9]{2}\.zip' -mtime +3
  1. -name使用球状表达式, 又名通配符。你想要的是什么 -regex
  2. 要按照您的意愿使用间隔,您 需要告诉find使用扩展 正则表达式通过 -regextype posix-extended标志
  3. 你需要逃离时期 因为在正则表达式中有一段时间 任何单一的特殊含义 字符。你想要的是一个 由\.
  4. 表示的文字句点
  5. 仅匹配那些文件 更多超过3天,您需要在数字前加+作为 在-mtime +3
  6. 概念证明

    $ find . -regextype posix-extended -regex '^.*test\.log\.[0-9]{4}-[0-9]{2}-[0-9]{2}\.zip'
    ./test.log.1234-12-12.zip
    

答案 1 :(得分:14)

使用-regex not -name,并注意正则表达式与查找的内容匹配,例如“/home/test/test.log”不是“test.log”

答案 2 :(得分:9)

开始于:

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

您可能不需要正则表达式,请尝试:

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

您需要 +1 才能匹配1,2,3 ......

答案 3 :(得分:7)

使用-regex

从手册页:

-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'.

另外,我认为find不支持\d等正则表达式扩展。您需要使用[0-9]

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

答案 4 :(得分:1)

只是很少详细说明搜索目录和文件的正则表达式

找一个名为book

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

查找名为book word

的文件
find . -name "*book*" -type f