macos 为什么这个正则表达式不起作用: find ./ -regex '.*\(m\|h\)$
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5905493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
why isn't this regex working : find ./ -regex '.*\(m\|h\)$
提问by Greg
Why isn't this regex working?
为什么这个正则表达式不起作用?
find ./ -regex '.*\(m\|h\)$
I noticed that the following works fine:
我注意到以下工作正常:
find ./ -regex '.*\(m\)$'
But when I add the "or a h at the end of the filename" by adding \|h
it doesn't work. That is, it should pick up all my *.m
and *.h
files, but I am getting nothing back.
但是当我在文件名末尾添加“或啊”时,\|h
它不起作用。也就是说,它应该拿起我所有的*.m
和*.h
文件,但我得到任何回报。
I am on Mac OS X.
我在 Mac OS X 上。
回答by Mikel
On Mac OS X, you can't use \|
in a basic regular expression, which is what find
uses by default.
在 Mac OS X 上,您不能\|
在基本正则表达式中使用,这是find
默认使用的。
[basic] regular expressions differ in several respects. | is an ordinary character and there is no equivalent for its functionality.
[基本] 正则表达式在几个方面有所不同。| 是一个普通字符,它的功能没有等价物。
The easiest fix in this case is to change \(m\|h\)
to [mh]
, e.g.
在这种情况下最简单的解决方法是更改\(m\|h\)
为[mh]
,例如
find ./ -regex '.*[mh]$'
Or you could add the -E
option to tell find to use extended regular expressions instead.
或者您可以添加-E
选项来告诉 find 使用扩展的正则表达式。
find -E ./ -regex '.*(m|h)$'
Unfortunately -E
isn't portable.
不幸的-E
是不便携。
Also note that if you only want to list files ending in .m
or .h
, you have to escape the dot, e.g.
另请注意,如果您只想列出以.m
or结尾的文件.h
,则必须对点进行转义,例如
find ./ -regex '.*\.[mh]$'
If you find this confusing (me too), there's a great reference table that shows which features are supported on which systems.
如果您觉得这令人困惑(我也是),这里有一个很好的参考表,其中显示了哪些系统支持哪些功能。
回答by Wes
A more efficient solution is to use the -o
flag:
更有效的解决方案是使用-o
标志:
find . -type f \( -name "*.m" -o -name "*.h" \)
but if you want the regex use:
但如果你想要正则表达式使用:
find . -type f -regex ".*\.[mh]$"
回答by IDBUYTHATFORADOLLAR
Okay this is a little hacky but if you don't want to wrangle the regex limitations of find on OSX, you can just pipe find's output to grep:
好的,这有点 hacky 但如果您不想在 OSX 上纠结 find 的正则表达式限制,您可以将 find 的输出通过管道传递给 grep:
find . | grep ".*\(\h\|m\)"
回答by tchrist
What's wrong with
怎么了
find . -name '*.[mh]' -type f
If you want fancy patterns, then use find2perland hack the pattern.
如果你想要花哨的模式,那么使用find2perl并破解模式。