查找和正则表达式

Sar*_*use 4 find regular-expression

这个 find 表达式我做错了什么?

; touch ook ooks
; find . -name 'ook' -or -name 'ooks' -type f
./ook
./ooks
; find . -name 'ook[s]?' -type f      
[returns nothing]
; echo $?
0
Run Code Online (Sandbox Code Playgroud)

cas*_*cas 9

您将正则表达式与 shell 搜索模式混淆了。

? 在 shell 中表示任何单个字符。

? 在正则表达式中表示前一个字符(或子模式)是可选的。

尝试:

find . -regex '.*ooks?' -type f

从查找手册页:

       -正则表达式模式
              文件名匹配正则表达式模式。这是一场比赛
              在整个路径上,而不是搜索。例如匹配一个文件
              名为`./fubar3',你可以使用正则表达式`.*bar.' 或者
              `.*b.*3',但不是 `f.*r3'。理解的正则表达式
              by find 默认是 Emacs 正则表达式,但这可以
              使用 -regextype 选项进行更改。


Tho*_*hor 6

这个答案至少适用于 GNU find。

-name使用 shell 模式匹配,如果您想进行正则表达式匹配,请-regex改用:

 find . -regex '.*ook[s]?' -type f
Run Code Online (Sandbox Code Playgroud)

-regex使用 emacs 正则表达式匹配整个路径。正则表达式类型可以用-regextype.