【问题标题】:Regular Expression in Find commandFind 命令中的正则表达式
【发布时间】:2015-08-27 03:28:56
【问题描述】:

我想列出以数字开头并以“.c”扩展名结尾的文件。以下是使用的 find 命令。但是,它不给 预期的输出。

命令:

find -type f -regex "^[0-9].*\\.c$"

【问题讨论】:

  • . 匹配任何字符。尝试[.]\. 另外,-regex 匹配完整路径,而不是文件名。
  • 我已经尝试过了。但它不起作用
  • @Mohan 正如 knittl 所说,find 不只是打印文件名,所以这样的事情会起作用:find -type f -regex '^[.][/][0-9].*.c'
  • 这也没有给出预期的输出。因为“.//..../”。只有在同一目录中执行命令时,您的语法才有效。对于递归搜索,以下是给出预期输出的命令。 find -type f -regex ".*/[0-9].*\.c$".
  • 您可以在这里省略正则表达式,因为它似乎使事情变得复杂,而只需使用 glob 模式,如find -type f -name '[0-9]*.c'...

标签: regex linux bash shell unix


【解决方案1】:

这是因为正则表达式选项适用于完整路径,而您只指定了文件名。来自man find

   -regex pattern
         File name matches regular expression pattern.  This is a match on the whole
         path, not a search.  For example, to match a file named './fubar3', you can use
         the  regular  expression  '.*bar.'  or  '.*b.*3',  but  not 'f.*r3'. 
         The regular expressions understood by find are by default Emacs Regular
         Expressions, but this can be changed with the -regextype option.

试试这个:

find -type f -regex ".*/[0-9][^/]+\.c$"

您在其中明确查找一个字符串,其中 “文件名的格式遵循以斜杠结尾的任何字符串”

更新:我对正则表达式进行了更正。我将文件名中的.* 更改为[^\]+,因为在 “任何以斜线结尾的字符串” 我们不想在字符串的该部分中找到斜线,因为它不会是一个文件名,但另一个目录!

注意:匹配的.* 可能非常有害...

【讨论】:

    【解决方案2】:

    只需使用-name 选项。正如文档所说,它接受路径名的最后一个组件的模式:

    -name pattern
    
             True if the last component of the pathname being examined matches
             pattern.  Special shell pattern matching characters (``['',
             ``]'', ``*'', and ``?'') may be used as part of pattern.  These
             characters may be matched explicitly by escaping them with a
             backslash (``\'').
    

    所以:

    $ find -type f -name "[0-9]*.c"
    

    应该可以。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-06
      • 1970-01-01
      • 2015-12-20
      • 2012-10-29
      • 1970-01-01
      • 2014-07-07
      • 1970-01-01
      相关资源
      最近更新 更多