正则表达式匹配linux中的字符串"find"命令

Reu*_*ani 21 regex linux find

我正在尝试以下方法以递归方式查找以.py或者结尾的文件.py.server:

$ find -name "stub*.py(|\.server)"
Run Code Online (Sandbox Code Playgroud)

但这不起作用.

我尝试过各种变化:

$ find -name "stub*.(py|py\.server)"
Run Code Online (Sandbox Code Playgroud)

它们也不起作用.

一个简单的find -name "*.py"工作,所以怎么regex没有?

dev*_*ull 35

说:

find . \( -name "*.py" -o -name "*.py.server" \)
Run Code Online (Sandbox Code Playgroud)

这样说会导致文件名匹配*.py*.py.server.

来自man find:

   expr1 -o expr2
          Or; expr2 is not evaluated if expr1 is true.
Run Code Online (Sandbox Code Playgroud)

编辑:如果要指定正则表达式,请使用以下-regex选项:

find . -type f -regex ".*\.\(py\|py\.server\)"
Run Code Online (Sandbox Code Playgroud)


Chr*_*our 6

查找可以采用正则表达式模式:

$ find . -regextype posix-extended -regex '.*[.]py([.]server)?$' -print
Run Code Online (Sandbox Code Playgroud)

选项:

-regex模式

文件名与正则表达式模式匹配.这是整个路径上的匹配,而不是搜索.例如,匹配名为./fubar3', you can use the regular expression.*bar 的文件.或 .*b.*3', but notf.*r3'.find所理解的正则表达式默认为Emacs Regular Expressions,但可以使用-regextype选项进行更改.

-print True;

在标准输出上打印完整文件名,然后换行.如果您将find的输出传递给另一个程序,并且您搜索的文件可能包含换行符的可能性最小,那么您应该认真考虑使用-print0选项而不是-print.有关如何处理文件名中的异常字符的信息,请参见"异常文件"部分.

-regextype类型

更改-regex和-iregex测试所理解的正则表达式语法,这些语法稍后会出现在命令行中.当前实现的类型是emacs(这是默认值),posix-awk,posix-basic,posix-egrep和posix-extended.

更清晰的描述或选项.不要忘记通过阅读man find或找到所有信息info find.


Vor*_*ung 5

find-name不使用正则表达式,这是 Ubuntu 12.04 手册页的摘录

-name pattern
              Base of  file  name  (the  path  with  the  leading  directories
              removed)  matches  shell  pattern  pattern.   The metacharacters
              (`*', `?', and `[]') match a `.' at the start of the  base  name
              (this is a change in findutils-4.2.2; see section STANDARDS CON?
              FORMANCE below).  To ignore a directory and the files under  it,
              use  -prune; see an example in the description of -path.  Braces
              are not recognised as being special, despite the fact that  some
              shells  including  Bash  imbue  braces with a special meaning in
              shell patterns.  The filename matching is performed with the use
              of  the  fnmatch(3)  library function.   Don't forget to enclose
              the pattern in quotes in order to protect it from  expansion  by
              the shell.
Run Code Online (Sandbox Code Playgroud)

所以采用的模式-name更像是一个 shell glob 而根本不像一个正则表达式

如果我想通过正则表达式找到我会做类似的事情

find . -type f -print | egrep 'stub(\.py|\.server)'
Run Code Online (Sandbox Code Playgroud)

  • 声明 *find 不使用正则表达式 * 显然是错误的(虽然说 *``-name`` 所采用的模式更像是一个 shell glob* 是正确的)。 (2认同)