bash 使用通配符排除具有特定后缀的文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/11437005/
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
Using wildcards to exclude files with a certain suffix
提问by Ramesh Samane
I am experimenting with wildcards in bash and tried to list all the files that start with "xyz" but does not end with ".TXT" but getting incorrect results.
我正在 bash 中尝试使用通配符,并尝试列出所有以“xyz”开头但不以“.TXT”结尾但得到不正确结果的文件。
Here is the command that I tried:
这是我尝试过的命令:
$ ls -l xyz*[!\.TXT]
It is not listing the files with names "xyz" and "xyzTXT" that I have in my directory. However, it lists "xyz1", "xyz123".
它没有列出我的目录中名称为“xyz”和“xyzTXT”的文件。但是,它列出了“xyz1”、“xyz123”。
It seems like adding [!\.TXT]after "xyz*" made the shell look for something that start with "xyz" and has at least one character after it.
似乎[!\.TXT]在“xyz*”之后添加使外壳程序寻找以“xyz”开头并在其后至少有一个字符的内容。
Any ideas why it is happening and how to correct this command? I know it can be achieved using other commands but I am especially interested in knowing why it is failing and if it can done just using wildcards.
任何想法为什么会发生以及如何更正此命令?我知道它可以使用其他命令来实现,但我特别想知道它为什么失败以及它是否可以只使用通配符来完成。
采纳答案by Zagorax
I don't think this is doable with only wildcards.
我认为仅使用通配符是行不通的。
Your command isn't working because it means:
您的命令不起作用,因为它意味着:
Match everything that has xyzfollowed by whatever you want and it must not end with sequent character: \, .,Tand X. The second Tdoesn't count as far as what you have inside []is read as a family of character and not as a string as you thought.
匹配了一切xyz之后任何你想要的,它不能与序贯字符结尾:\,.,T和X。第二个T不算在内,因为您将其中的[]内容读作字符族而不是您想象的字符串。
You don't either need to 'escape' .as long as it has no special meaning inside a wildcard.
.只要通配符中没有特殊含义,您就不需要“转义” 。
At least, this is my knowledge of wildcards.
至少,这是我对通配符的了解。
回答by Nahuel Fouilleul
These commands will do what you want
这些命令会做你想做的
shopt -s extglob
ls -l xyz!(*.TXT)
shopt -u extglob
The reason why your command doesn't work is beacause xyz*[!\.TXT] which is equivalent to xyz*[!\.TX] means xyz followed by any sequence of character (*) and finally a character in set {!,\,.,T,X} so matches 'xyzwhateveryouwant!' 'xyzwhateveryouwant\' 'xyzwhateveryouwant.' 'xyzwhateveryouwantT' 'xyzwhateveryouwantX'
您的命令不起作用的原因是因为 xyz*[!\.TXT] 相当于 xyz*[!\.TX] 表示 xyz 后跟任何字符序列 (*) 和最后一个字符集 {! ,\,.,T,X} 所以匹配 'xyzwhateveryouwant!' 'xyzwhateveryouwant\' 'xyzwhateveryouwant。' 'xyzwhateveryouwantT' 'xyzwhateveryouwantX'
EDIT: where whateveryouwant does not contain any of !\.TX
编辑: where whatyouwant 不包含任何 !\.TX

