包含 'x' 的 Unix grep 正则表达式但不包含“y”
我需要一个用于 unix grep 的单遍正则表达式,其中包含 alpha,但不包含 beta。
grep 'alpha' <> | grep -v 'beta'
I need a single-pass regex for unix grep that contains, say alpha, but does not contain beta.
grep 'alpha' <> | grep -v 'beta'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这里的其他答案展示了一些可以扭曲不同种类的正则表达式来做到这一点的方法,尽管我认为答案确实是,一般来说,“不要这样做”。与使用您所使用的任何语言的布尔逻辑组合两个正则表达式相比,此类正则表达式更难阅读,而且执行起来可能更慢。如果您在 unix shell 提示符下使用 grep 命令,只需将一个命令的结果通过管道传输到另一个命令即可:
我一直使用这种构造来筛选来自 grep 的过多结果。如果您知道哪个结果集较小,请将其放在管道中以获得最佳性能,因为第二个命令只需处理第一个命令的输出,而不是整个输入。
The other answers here show some ways you can contort different varieties of regex to do this, although I think it does turn out that the answer is, in general, “don’t do that”. Such regular expressions are much harder to read and probably slower to execute than just combining two regular expressions using the boolean logic of whatever language you are using. If you’re using the
grep
command at a unix shell prompt, just pipe the results of one to the other:I use this kind of construct all the time to winnow down excessive results from
grep
. If you have an idea of which result set will be smaller, put that one first in the pipeline to get the best performance, as the second command only has to process the output from the first, and not the entire input.好吧,我们都在发布答案,这里是 awk ;-)
IHTH。
Well as we're all posting answers, here it is in awk ;-)
IHTH.
^((?!beta).)*alpha((?!beta).)*$
我认为可以解决这个问题。^((?!beta).)*alpha((?!beta).)*$
would do the trick I think.我很确定这对于真正的正则表达式是不可能的。
[^y]*x[^y]*
示例将匹配 yxy,因为 * 允许零个或多个非 y 匹配。编辑:
实际上,这似乎有效:
^[^y]*x[^y]*$
。它的基本意思是“匹配以零个或多个非 y 字符开头,然后有一个 x,然后以零个或多个非 y 字符结尾的任何行”。I'm pretty sure this isn't possible with true regular expressions. The
[^y]*x[^y]*
example would match yxy, since the * allows zero or more non-y matches.EDIT:
Actually, this seems to work:
^[^y]*x[^y]*$
. It basically means "match any line that starts with zero or more non-y characters, then has an x, then ends with zero or more non-y characters".尝试使用排除运算符:
[^y]*x[^y]*
Try using the excludes operator:
[^y]*x[^y]*
问:如果
y
是目录,如何在没有管道的 grep 中匹配x
而不是y
A:
grep x --exclude- dir='y'
Q: How to match
x
but noty
in grep without pipe ify
is a directoryA:
grep x --exclude-dir='y'
最简单的解决方案:
请注意空格和双引号。
Simplest solution:
Please take care of gaps and double quotes.