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
How to use regex in file find
提问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
-name
uses globularexpressions, aka wildcards. What you want is-regex
- To use intervals as you intend, you
need to tell
find
to use Extended Regular Expressionsvia the-regextype posix-extended
flag - 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
\.
- To match only those files that are
greaterthan 3 days old, you need to prefix your number with a
+
as in-mtime +3
.
-name
使用全局表达式,又名通配符。你想要的是-regex
- 要按预期使用间隔,您需要通过
标志告诉
find
使用扩展正则表达式-regextype posix-extended
- 您需要转义句点,因为在正则表达式中,句点具有任何单个字符的特殊含义。你想要的是一个字面意思表示为
\.
- 为了只匹配那些文件
较大超过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 find
supports 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