【问题标题】:find command with -regex in FreeBSD在 FreeBSD 中使用 -regex 查找命令
【发布时间】:2014-01-05 02:30:34
【问题描述】:

我已经完成了quite a lot of research 并尝试了列出的每一种技术(有些在 freebsd/osx 上不起作用),但是当我使用 find 命令进行最简单的搜索时,它返回为空。

我有一个目录,其中包含以下文件:

file_name_one.ext
_something.ext
some_other_file.ext
maybe_one_more.ext

我尝试了以下方法来查找所有包含下划线的文件:

find . -regex "_"
find . -regex _
find . -name "_"
find . -regex "_"
find . -regex "\_"
find . -regex "_.*"
find . -regex "\_,*"
find . -regex "\_.*"
find . -name "_" -print 
find . -regex '_'
find . -regex '\(_\)'
find . -regex '$\137'
find . -regex '\137'
find . -regex '(_)'
find . -regex '\x5F'
find . -regex '.*\x5F'
find . -regex '.*/[\x5F/]
find . -regex '.*/[\x5F/]'
find . -regex '/_/'
find -E . -regex '.*/[^_/]'
find -E . -regex '\137'
find -E . -regex '\137' -print
find -E . -regex '$\137'
find -E . -regex '(_)'
find . -regextype sed -regex "_"

没有运气 ……这到底是怎么回事?为什么它不匹配任何包含下划线的文件?

【问题讨论】:

  • 试试find . -name '*_*'find . -regex '.*_.*' 手册页说正则表达式需要匹配整个路径。实际上,find . -regex '.*/.*_.*' 可能更好,这样您就不会无意中匹配 ./a_b/c 之类的路径

标签: regex macos terminal find freebsd


【解决方案1】:

让我们将问题分解为重要的部分。你想:

  • 查找文件
  • 文件名中有下划线。

如果只查找常规文件,请使用-type f。要查找包含特定字符的名称,请使用 -name 和 shell 模式。

来自文档;

 -type t
         True if the file is of the specified type.  Possible file types
         are as follows:

         b       block special
         c       character special
         d       directory
         f       regular file
         l       symbolic link
         p       FIFO
         s       socket

 -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 -s . -type f -name '*_*'

-s 选项用于对结果进行排序。

如果你想匹配整个路径并且你需要一个不能在shell模式中重现的表达式,你应该使用-regex

【讨论】:

    【解决方案2】:

    或者您可以使用以下任何正则表达式来增加它的趣味性:

    find . -type f -regex ".*_.*"
    find . -type f -regex '.*_.*'
    find . -type f -regex .*_.*
    

    您在第一个示例中遗漏了一些内容可能出现在下划线之前/之后,因此.*,其中. 等于任何字符(换行符除外),* 等于零个或多个字符。在这种情况下,无论您使用 "' 还是表达式周围的任何内容都无关紧要。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-18
      • 1970-01-01
      • 1970-01-01
      • 2019-12-24
      • 1970-01-01
      • 2015-07-21
      • 1970-01-01
      相关资源
      最近更新 更多