如何在 bash 中找到所有不以给定前缀开头的文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21368838/
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-18 09:22:46  来源:igfitidea点击:

How do I find all files that do not begin with a given prefix in bash?

bashshellunixgrepfind

提问by Robert

I have a bunch of files in a folder:

我在一个文件夹中有一堆文件:

foo_1 
foo_2
foo_3
bar_1
bar_2
buzz_1
...

I want to find all the files that do notstart with a given prefix and save the list to a text file. Here is an example for the files that dohave a given prefix:

我想找到所有以给定前缀开头的文件并将列表保存到文本文件中。下面是该文件的一个例子有一个给定的前缀:

find bar_* > Positives.txt

采纳答案by Jens

This should do the trick in any shell

这应该可以在任何 shell 中解决问题

ls | grep -v '^prefix'

The -v option inverts grep's search logic, making it filter out all matches. Using grep instead of find you can use powerful regular expressions instead of the limited glob patterns.

-v 选项反转 grep 的搜索逻辑,使其过滤掉所有匹配项。使用 grep 代替 find 您可以使用强大的正则表达式代替有限的 glob 模式。

回答by lurker

If you're doing subdirectories as well:

如果你也在做子目录:

find . ! -name "bar_*"

回答by grebneke

You want to find filenames notstarting with bar_*?

您想查找bar_*?开头的文件名?

recursive:

递归:

find ! -name 'bar_*' > Negatives.txt

top directory:

顶级目录:

find -maxdepth 1 ! -name 'bar_*' > Negatives.txt

回答by Etienne

Using bash and wildcards: ls [!bar_]*. There is a caveat: the order of the letters is not important, so rab_something.txtwill not be listed.

使用 bash 和通配符: ls [!bar_]*. 有一个警告:字母的顺序并不重要,因此rab_something.txt不会列出。

回答by Benjamin W.

With extended globs:

使用扩展球:

shopt -s extglob
ls !(bar_*) > filelist.txt

The !(pattern)matches anything butpattern, so !(bar_*)is any filename that does notstart with bar_.

!(pattern)匹配什么,但是pattern,这样!(bar_*)是没有任何文件名下手bar_

回答by Nagev

In my case I had an extra requirement, the files must end with the .pyextension. So I use:

就我而言,我有一个额外的要求,文件必须以.py扩展名结尾。所以我使用:

find . -name "*.py" | grep -v prefix_

In your case, to just exclude files with prefix_:

在您的情况下,只需排除文件prefix_

find . | grep -v prefix_

Note that this includes all sub-directories. There are many ways to do this, but it can be easy to remember for those already familiar with findand grep -vwhich excludes results.

请注意,这包括所有子目录。有很多方法可以做到这一点,但对于那些已经熟悉findgrep -v排除结果的人来说,它很容易记住。