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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5249779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:15:44  来源:igfitidea点击:

How to use regex in file find

bashunix

提问by Tree

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

我试图查找 3 天或更长时间前的所有文件和所有文件。

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?

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

回答by SiegeX

find /home/test -regextype posix-extended -regex '^.*test\.log\.[0-9]{4}-[0-9]{2}-[0-9]{2}\.zip' -mtime +3
  1. -nameuses globularexpressions, aka wildcards. What you want is -regex
  2. To use intervals as you intend, you need to tell findto use Extended Regular Expressionsvia the -regextype posix-extendedflag
  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 greaterthan 3 days old, you need to prefix your number with a +as in -mtime +3.
  1. -name使用全局表达式,又名通配符。你想要的是 -regex
  2. 要按预期使用间隔,您需要通过 标志告诉find使用扩展正则表达式-regextype posix-extended
  3. 您需要转义句点,因为在正则表达式中,句点具有任何单个字符的特殊含义。你想要的是一个字面意思表示为\.
  4. 为了只匹配那些文件 较大超过3天的时候,你需要用一个前缀的号码+-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

回答by Erik

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"

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

回答by DigitalRoss

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 +1in order to match 1, 2, 3 ...

您将需要+1以匹配 1, 2, 3 ...

回答by dogbane

Use -regex:

使用-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 findsupports regex extensions such as \d. You need to use [0-9].

另外,我不相信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'

回答by Shafiq

Just little elaboration of regex for search a directory and file

只是对用于搜索目录和文件的正则表达式进行了一点阐述

Find a directroy with name like book

查找名称为 book 的目录

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

Find a file with name like book word

查找名称类似于 book word 的文件

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