Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unix grep regex containing 'x' but not containing 'y'

I need a single-pass regex for unix grep that contains, say alpha, but does not contain beta.

grep 'alpha' <> | grep -v 'beta' 
like image 892
Wilderness Avatar asked May 19 '11 18:05

Wilderness


People also ask

Can you use regex with grep?

GNU grep supports three regular expression syntaxes, Basic, Extended, and Perl-compatible. In its simplest form, when no regular expression type is given, grep interpret search patterns as basic regular expressions. To interpret the pattern as an extended regular expression, use the -E ( or --extended-regexp ) option.

Can you use wildcards with grep?

Wildcards. If you want to display lines containing the literal dot character, use the -F option to grep.

How escape grep regex?

This is described in Regular Expressions (regexp). If you include special characters in patterns typed on the command line, escape them by enclosing them in single quotation marks to prevent inadvertent misinterpretation by the shell or command interpreter.

How do I grep a pattern in Linux?

To find a pattern that is more than one word long, enclose the string with single or double quotation marks. The grep command can search for a string in groups of files. When it finds a pattern that matches in more than one file, it prints the name of the file, followed by a colon, then the line matching the pattern.


2 Answers

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.

like image 180
nohat Avatar answered Oct 18 '22 05:10

nohat


Well as we're all posting answers, here it is in awk ;-)

awk '/x/ && !/y/' infile 

I hope this helps.

like image 23
shellter Avatar answered Oct 18 '22 04:10

shellter