bash 如何查找除给定名称之外的文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19020759/
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 find files except given name?
提问by user2818137
I have a dir with:
我有一个目录:
- bla-bla-bla1.tar.7z
- bla-bla-bla2.tar.7z
- bla-bla-bla3.tar.7z
- _bla-bla-bla_foo.tar.7z
- bla-bla-bla1.tar.7z
- bla-bla-bla2.tar.7z
- bla-bla-bla3.tar.7z
- _bla-bla-bla_foo.tar.7z
I need to find and delete all files ".7z" except "_.7z"
我需要查找并删除除“_.7z”之外的所有文件“ .7z”
I use find /backups/ -name "*.7z" -type f -mtime +180 -delete
我使用 find /backups/ -name "*.7z" -type f -mtime +180 -delete
How i can do it?
我该怎么做?
回答by chepner
Another approach is to use an additional, negated primary with find
:
另一种方法是使用一个额外的、否定的主find
:
find /backups/ -name "*.7z" ! -name '_.7z' -type f -mtime +180 -delete
The simple regex in the other answers is better for your use case, but this demonstrates a more general approach using the !
operator available to find
.
其他答案中的简单正则表达式更适合您的用例,但这演示了使用!
可用于find
.
回答by shx2
In regular expressions, the ^
operator means "any character except for". Thus [^_]
means "any character except for _". E.g.:
在正则表达式中,^
运算符的意思是“任何字符除外”。因此[^_]
表示“除 _ 之外的任何字符”。例如:
"[^_]*.7z"
So, if your intention is to exclude files startingwith _
, your full command line would be:
所以,如果你的目的是要排除的文件开始使用_
,您的完整的命令行应该是:
find /backups/ -name "[^_]*.7z" -type f -mtime +180 -delete
If you'd like to exclude anyoccerance of _
, you can use the and
and not
operators of find
, like:
如果您想排除 的任何occerance _
,您可以使用 的and
和not
运算符find
,例如:
find . -name "*.7z" -and -not -name "*_*"
回答by Nancy
It should be
它应该是
find . -name "*[^_].7z"
回答by Sahil M
A quick way given you have bash 4.2.25, is to simply use bash pattern matching to remove all .7z, but the ones having _.7z, like this:
给定 bash 4.2.25 的一种快速方法是简单地使用 bash 模式匹配来删除所有 .7z,但具有 _.7z 的那些,如下所示:
touch a.7z b.7z c.7z d_.7z e_.7z f.txt
rm *[^_].7z