正则表达式 - Linux上,如何让find命令支持正则查找?
本文介绍了正则表达式 - Linux上,如何让find命令支持正则查找?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
描述问题
比如我构造一个find命令find . -type f -name 'autojump*'
, 理所当然地想,正则表达式从-name
这个选项中注入,因为这是最自然的思考
find中,可以注入的都是shell通配符系列,但是shell通配符表达能力不是很强(尤其有一个复杂的需求时)
但是我搜索了一番,发现解决方法都不太自然,另外find由于要兼容许多Unix/Linux平台,导致其不是很放得开,
或许有更好的解决方法
上下文环境
Linux-find,
正则为: ERE or Perl风格兼容
我想构造的正则示例:
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搜索结果:
问题简化
解决方案
-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'
这篇关于正则表达式 - Linux上,如何让find命令支持正则查找?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文