azalea says

Linux查找与特定正则表达式匹配的文件名

前面转载过一篇文章介绍find和grep命令,其中提到

grep命令可以用来查找文件中的特定内容,

find path -name pattern可以用来查找特定的文件名,但是只能用shell里的通配符匹配,包括*,?和[]

但是通配符能够匹配的模式有限。

研究了半天,终于找到了查找匹配特定正则表达式的文件名的命令:

find path -regex "regularexpression"

man find对-regex的定义是

-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.

比如:我要查找当前目录中长成这样的文件名: 以ath-MIR开头,后面接3个数字再接0或1个小写字母,e.g. ath-MIR165a

命令如下:

find . -regex “./ath.MIR[0-9][0-9][0-9][a-z]?”

有几点注意:

a.匹配的是完整路径,即包括./

b.-regex默认的正则表达式类型是emacs,而emacs正则表达式的语法中没有{},这在有些正则表达式中表示重复次数,如python。因此匹配3个数字只好写成[0-9][0-9][0-9]。而且emacs正则表达式好像也没有d来匹配数字,因此用[0-9]表示。

c.-regex的正则表达式类型可以用-regextype修改。除了默认的emacs类型外,还有 posix-awk,posix-basic, posix-egrep 和posix-extended. emacs正则表达式的语法在这里可以找到。

d.我要匹配的文件名中有-,不知道为什么不能直接写在正则表达式中, “./ath-MIR[0-9][0-9][0-9][a-z]?”找不到匹配结果。高人请留言指教下!

linux ubuntu 文件 正则表达式 · Tweet Edit