且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-21 11:07:24

 查找/主页/测试-regextype POSIX扩展-regex'^ *测试\\ .LOG \\。[0 -9] {4}  -  [0-9] {2}  -  [0-9] {2} \\拉链'-mtime +3


  1. -name 使用的球状的前pressions,
    又名通配符。你需要的是
    -regex ​​

  2. 要为你打算,您使用的时间间隔
    需要告诉找到使用的扩展
    通过经常防爆pressions

    -regextype POSIX扩展标志

  3. 您需要跳脱出周期
    因为在正则表达式一个时期有
    任何单一的特殊含义
    字符
    的。你需要的是一个
    文字期内表示\\。

  4. 要只匹配那些文件
    大于的比老3天,你需要preFIX以 + 为你的电话号码
    -mtime +3

概念验证

  $找到。 -regextype POSIX扩展-regex'^ *测试\\ .LOG \\ [0-9] {4}  -  [0-9] {2}  -  [0-9] {2} \\拉链。
./test.log.1234-12-12.zip

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?

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