【问题标题】:How to search filenames by regex with "find"如何使用“查找”通过正则表达式搜索文件名
【发布时间】:2011-03-09 17:32:46
【问题描述】:

我试图查找所有日期为 3 天或更早的文件。

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

它没有列出任何东西。它有什么问题?

【问题讨论】:

    标签: bash unix


    【解决方案1】:
    find /home/test -regextype posix-extended -regex '^.*test\.log\.[0-9]{4}-[0-9]{2}-[0-9]{2}\.zip' -mtime +3
    
    1. -name 使用 globular 表达式, 又名通配符。你想要的是 -regex
    2. 要按您的意愿使用间隔,您 需要告诉find 使用扩展 正则表达式通过 -regextype posix-extended标志
    3. 您需要避开句号 因为在正则表达式中,句号有 任何单曲的特殊含义 字符。你想要的是一个 \. 表示的文字句点
    4. 仅匹配那些 大于超过 3 天,您需要在您的号码前加上 + 作为前缀 在-mtime +3

    概念证明

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

    【讨论】:

    • 如果您碰巧在 OS X 上运行,请使用-Efind -E . -regex 'theregex' 利用扩展(现代)正则表达式。
    • [0-9]{2} 在 macOS 上对我不起作用,我不得不使用 [0-9][0-9]
    • 需要扩展以使用可选组,即find -E . -iregex '^.*\.js(\.map)?$'
    • @Chris see '-regextype posix-extended'
    • @SiegeX 我之前的评论是为了以防万一有人发现知道为了使用可选组,您需要启用 posix-extended 并举例说明它的样子很有用。谢谢你的回答。
    【解决方案2】:

    开始于:

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

    你可能不需要正则表达式,试试:

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

    您需要 +1 以匹配 1、2、3 ...

    【讨论】:

      【解决方案3】:

      使用-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】:

        使用 -regex 而不是 -name,并注意正则表达式与 find 将打印的内容相匹配,例如“/home/test/test.log”不是“test.log”

        【讨论】:

        • 感谢您和@dogbane 指出需要完整路径匹配。
        【解决方案5】:

        只是对搜索目录和文件的正则表达式进行了少许阐述

        找一个名字像书的目录

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

        找一个名字像书字的文件

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-01-17
          • 1970-01-01
          • 1970-01-01
          • 2010-10-09
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多