I need a single-pass regex for unix grep that contains, say alpha, but does not contain 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'
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:
grep "alpha" | grep -v "beta"
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.
-A
, -B
and -C
options that grep
has.
Commented
Sep 8, 2015 at 14:20
beta
.
grep -l "alpha" | grep -v "beta"
. The first grep
returns the file names.
beta.py
which contain the string alpha
. These should be returned in the results but aren't. It could be worked around with `grep "alpha" | grep -v "[*:]+:.*beta" or similar, I guess.
Well as we're all posting answers, here it is in awk ;-)
awk '/x/ && !/y/' infile
IHTH.
&&
d reg-exp mathces. thanks for looking at my answer. Good luck to all.
^((?!beta).)*alpha((?!beta).)*$
would do the trick I think.
grep
doesn't support syntax like that!
perldoc perlre
for an explanation of lookahead assertions.
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".
Try using the excludes operator: [^y]*x[^y]*
[^y]*
matches the string y
because there are zero non-y characters in that string.
alpha
but not beta
. The string alphabeta
does not meet the questioner's criterion (it contains the string beta
) yet your regular expression will return true because, before the substring alpha
, there are zero or more occurrences of the string beta
.
x
but not y
in grep without pipe if y
is a directorygrep x --exclude-dir='y'
Simplest solution:
grep "alpha" * | grep -v "beta"
Please take care of gaps and double quotes.