Linux上,如何让find命令支持正则查找?

描述问题

比如我构造一个find命令find . -type f -name 'autojump*', 理所当然地想,正则表达式从-name这个选项中注入,因为这是最自然的思考

find中,可以注入的都是shell通配符系列,但是shell通配符表达能力不是很强(尤其有一个复杂的需求时)

但是我搜索了一番,发现解决方法都不太自然,另外find由于要兼容许多Unix/Linux平台,导致其不是很放得开,

或许有更好的解决方法

上下文环境

  1. Linux-find,

  2. 正则为: ERE or Perl风格兼容

  3. 我想构造的正则示例: find . -type f -name 'autojump.(bash|zsh|sh)

重现

相关代码

查阅man文档,摘抄如下, 虽然支持, 但是貌似附带了若干使用条件(不免令人有点不爽)

 -regextype type
              Changes the regular expression syntax understood by -regex and
              -iregex tests which occur later on the command line.  To see
              which regular expression types are known, use -regextype help.
              The Texinfo documentation (see SEE ALSO) explains the meaning
              of and differences between the various types of regular
              expression.
 -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 -regextype help
find: Unknown regular expression type ‘help’; valid types are ‘findutils-default’, ‘awk’, ‘egrep’, ‘ed’, ‘emacs’, ‘gnu-awk’, ‘grep’, ‘posix-awk’, ‘posix-basic’, ‘posix-egrep’, ‘posix-extended’, ‘posix-minimal-basic’, ‘sed’.

报错信息

相关截图

已经尝试哪些方法仍然没有解决(附上相关链接)

Google搜索结果:

  1. https://www.google.com/webhp?...

问题简化

阅读 14.5k
2 个回答
-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.

这个参数会影响,-regex [pattern]的匹配行为,类似使用不同的方言来解析正则表达式。
经过我的实验,我觉得这么写

find . -regextype posix-extended -regex './autojump.(bash|zsh|sh)'
或者
find . -regextype posix-extended -regex './autojump.(ba|z)?sh'

./auto..../是不能省略的,find的正则匹配不能够只匹配部分,要匹配完全(理解)。

==update==
如果前面的路径很长,可以这样子匹配

find . -regextype posix-extended -regex '.*autojump.(ba|z)?sh'

如果使用find * 然后再配合egrep,lz你怎么看?

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题