简体   繁体   English

bash 中的正则表达式量词 --simple 与扩展匹配 {n} 次

[英]regex quantifiers in bash --simple vs extended matching {n} times

I'm using the bash shell and trying to list files in a directory whose names match regex patterns.我正在使用 bash shell 并尝试列出名称与正则表达式模式匹配的目录中的文件。 Some of these patterns work, while others don't.其中一些模式有效,而另一些则无效。 For example, the * wildcard is fine:例如, * 通配符就可以:

$ls FILE_*
FILE_123.txt    FILE_2345.txt   FILE_789.txt

And the range pattern captures the first two of these with the following:范围模式使用以下内容捕获其中的前两个:

$ls FILE_[1-3]*.txt
FILE_123.txt    FILE_2345.txt

but not the filename with the "7" character after "FILE_", as expected.不是像预期的那样在“FILE_”之后带有“7”字符的文件名。 Great.伟大的。 But now I want to count digits:但现在我想计算数字:

$ls FILE_[0-9]{3}.txt 
ls: FILE_[0-9]{3}.txt: No such file or directory

Shouldn't this give me the filenames with three numeric digits following "FILE_" (ie FILE_123.txt and FILE_789.txt , but not FILE_2345.txt ) Can someone tell me how I should be using the {n} quantifier (ie "match this pattern n times)?这不应该给我在"FILE_"之后的三个数字的文件名(即FILE_123.txtFILE_789.txt ,但不是FILE_2345.txt )有人可以告诉我我应该如何使用 {n} 量词(即“匹配这种模式n次)?

ls uses with glob pattern , you can not use {3} . lsglob pattern一起使用,您不能使用{3} You have to use FILE_[0-9][0-9][0-9].txt .你必须使用FILE_[0-9][0-9][0-9].txt Or, you could the following command.或者,您可以使用以下命令。

ls | grep -E "FILE_[0-9]{3}.txt"

Edit:编辑:

Or, you also use find command.或者,您也可以使用find命令。

find . -regextype egrep -regex '.*/FILE_[0-9]{3}\.txt'

The .*/ prefix is needed to match a complete path.需要.*/前缀来匹配完整路径。 On Mac OS X :在 Mac OS X 上:

find -E . -regex ".*/FILE_[0-9]{3}\.txt"

Bash filename expansion does not use regular expressions. Bash 文件名扩展不使用正则表达式。 It uses glob pattern matching , which is distinctly different, and what you're trying with FILE_[0-9]{3}.txt does brace expansion followed by filename expansion.它使用 glob 模式匹配,这是明显不同的,并且您正在尝试使用FILE_[0-9]{3}.txt 大括号扩展,然后是文件名扩展。 Even bash 's extended globbing feature doesn't have an equivalent to regular expression's {N} , so as already mentioned you have to use FILE_[0-9][0-9][0-9].txt即使bash扩展通配符功能也没有与正则表达式的{N}等效,因此如前所述,您必须使用FILE_[0-9][0-9][0-9].txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM