bash 从 shell 中的通配符搜索中排除字符串

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

Exclude a string from wildcard search in a shell

bashwildcard

提问by steigers

I am trying to exclude a certain string from a file search.

我试图从文件搜索中排除某个字符串。

Suppose I have a list of files: file_Michael.txt, file_Thomas.txt, file_Anne.txt.

假设我有一个文件列表:file_Michael.txt、file_Thomas.txt、file_Anne.txt。

I want to be able and write something like

我希望能够写出类似的东西

ls *<and not Thomas>.txt

to give me file_Michael.txt and file_Anne.txt, but not file_Thomas.txt.

给我 file_Michael.txt 和 file_Anne.txt,而不是 file_Thomas.txt。

The reverse is easy:

反过来很容易:

ls *Thomas.txt

Doing it with a single character is also easy:

使用单个字符也很容易:

ls *[^s].txt

But how to do it with a string?

但是如何用字符串来做呢?

Sebastian

塞巴斯蒂安

回答by Mark Byers

You can use find to do this:

您可以使用 find 来做到这一点:

$ find . -name '*.txt' -a ! -name '*Thomas.txt'

回答by ghostdog74

With Bash

使用 Bash

shopt -s extglob
ls !(*Thomas).txt

where the first line means "set extended globbing", see the manualfor more information.

第一行的意思是“设置扩展的通配符”,请参阅手册以获取更多信息。

Some other ways could be:

其他一些方法可能是:

find . -type f \( -iname "*.txt" -a -not -iname "*thomas*" \)

ls *txt |grep -vi "thomas"

回答by tripleee

If you are looping a wildcard, just skip the rest of the iteration if there is something you want to exclude.

如果您正在循环使用通配符,如果您想排除某些内容,只需跳过迭代的其余部分。

for file in *.txt; do
    case $file in *Thomas*) continue;; esac
    : ... do stuff with "$file"
done