大括號表達式在查找正規表示式中不起作用

大括號表達式在查找正規表示式中不起作用

我有兩個資料夾,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) 

相關內容