I've been trying to find a way to filter a line that has the word "lemon" and "rice" in it. I know how to find "lemon" or "rice" but not the two of them. They don't need to be next to the other, just one the same line of text.
I've been trying to find a way to filter a line that has the word "lemon" and "rice" in it. I know how to find "lemon" or "rice" but not the two of them. They don't need to be next to the other, just one the same line of text.
"Both on the same line" means "'rice' followed by random characters followed by 'lemon' or the other way around".
In regex that is
rice.*lemon
orlemon.*rice
. You can combine that using a|
:If you want to use normal regex instead of extended ones (
-E
) you need a backslash before the|
:For more words that quickly gets a bit lengthy and it's usually easier to use multiple calls of
grep
, for example:You can pipe the output of first grep command to another grep command and that would match both the patterns. So, you can do something like:
or,
Example:
Let's add some contents to our file:
What does the file contain:
Now, let's grep what we want:
We only get the lines where both the patterns match. You can extend this and pipe the output to another grep command for further "AND" matches.
Though the question asks for 'grep', I thought it might be helpful to post a simple 'awk' solution:
This can easily be extended with more words, or other boolean expressions besides 'and'.
Another idea to finding the matches in any order is using:
grep with
-P
(Perl-Compatibility) option and positive lookahead regex(?=(regex))
:or you can use below, instead:
.*?
means matching any characters.
that occurrences zero or more times*
while they are optional followed by a pattern(rice
orlemon
). The?
makes everything optional before it (means zero or one time of everything matched.*
)(?=pattern)
: Positive Lookahead: The positive lookahead construct is a pair of parentheses, with the opening parenthesis followed by a question mark and an equals sign.So this will return all lines with contains both
lemon
andrice
in random order. Also this will avoid of using|
s and doubledgrep
s.External links:
Advanced Grep Topics
Positive Lookahead – GREP for Designers
Will return matches for either foo or goo
If we admit that providing an answer that is not
grep
based is acceptable, like the above answer based onawk
, I would propose a simpleperl
line like:The search can be ignoring case with some/all of the words like
/lemon/i and /rice/i
. On most Unix/Linux machines perl is installed as well as awk anyway.Here's a script to automate the grep piping solution: