Grep for "Term" and Exclude "Another Term"
I Am Trying to Build a Grep Search That Searches for a Term but Exludes Lines Which Have a Second Term. I Wanted to Use Multiple -E "Pattern" Options but That...
I am trying to build a grep search that searches for a term but exludes lines which have a second term. I wanted to use multiple -e "pattern" options but that has not worked.
Here is an example of a command I tried and the error message it generated.
grep -i -E "search term" -ev "exclude term"
grep: exclude term: No such file or directory
It seams to me that the -v applies to all search terms / patterns. As this runs but then does not include search term in results.
grep -i -E "search term" -ve "exclude term"
5 Answers
To and expressions with grep you need two invocations:
grep -Ei "search term" | grep -Eiv "exclude term"
If the terms you are searching for are not regular expressions, use fixed string matching (-F) which is faster:
grep -F "search term" | grep -Fv "exclude term"
Short of invoking grep twice, there is only one way I can think of to accomplish this. It involves Perl Compatible Regular Expressions (PCRE) and some rather hacky look-around assertions.
To search for foo excluding matches that contain bar, you can use:
grep -P '(?=^((?!bar).)*$)foo'
Here's how it works:
(?!bar)matches anything that not bar without consuming characters from the string. Then.consumes a single character.^((?!bar).)*repeats the above from the start of the string (^) to the end of it ($). It will fail ifbaris encountered at any given point, since(?!bar)will not match.(?=^((?!bar).)*$)makes sure the string matches the previous pattern, without consuming characters from the string.foosearches for foo as usual.
I found this hack in Regular expression to match string not containing a word?. In Bart Kiers' answer, you can find a much more detailed explanation of how the negative look-ahead operates.
Must Read
If you want to do this in one pass, you can use awk instead of grep.
Format:
echo "some text" | awk '/pattern to match/ && !/pattern to exclude/'
Examples:
echo "hello there" | awk '/hello/ && !/there/'
Returns nothing.
echo "hello thre" | awk '/hello/ && !/there/'
Returns: hello thre
echo "hllo there" | awk '/hello/ && !/there/'
Returns nothing.