大括号表达式在查找正则表达式中不起作用

大括号表达式在查找正则表达式中不起作用

我有两个文件夹,CA01CA02当前文件夹下foo

foo -+
     |
     +-CA01
     |
     +-CA02

当我打字时

find . -regex ".*CA[0-9]+" -exec echo {} +

或者

find . -regex ".*CA[0-9][0-9]" -exec echo {} +

我有以下输出,这是预期的:

./CA01 ./CA02

但是当我输入

find . -regex ".*CA[0-9]\{2\}" -exec echo {} +

什么也没有出现,这实在是出乎意料。

因为默认情况下find使用 emacs 正则表达式。我可以使用以上所有内容来匹配这两个文件夹。

我在这里错过了什么吗?

答案1

您需要将 更改-regextype为支持重复计数的(即{2})。默认的emacs似乎不支持计数。默认的正则表达式类型模仿旧版本的 Emacs,它没有重复计数的语法。以下类型似乎对我有用。

例子

posix-egrep

$ find foo -regextype posix-egrep -regex ".*CA[0-9]{2}" -exec echo {} +
foo/CA02 foo/CA01

sed

$ find foo -regextype sed -regex ".*CA[0-9]\{2\}" -exec echo {} +
foo/CA02 foo/CA01

posix 扩展

$ find foo -regextype posix-extended -regex ".*CA[0-9]{2}" -exec echo {} +
foo/CA02 foo/CA01

还有其他的,但我没有再尝试。请参阅find手册页并搜索-regextype.

摘抄

-regextype type
       Changes  the  regular  expression  syntax  understood by -regex and 
       -iregex tests which occur later on the command line.  Currently
       implemented types are emacs (this is the default), posix-awk, 
       posix-basic, posix-egrep and posix-extended.

我的 find 版本

$ find -version
find (GNU findutils) 4.5.9
Copyright (C) 2010 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by Eric B. Decker, James Youngman, and Kevin Dalley.
Built using GNU gnulib version 1778ee9e7d0e150a37db66a0e51c1a56755aab4f
Features enabled: D_TYPE O_NOFOLLOW(enabled) LEAF_OPTIMISATION FTS(FTS_CWDFD) CBO(level=2) 

相关内容