Issue
I'm trying to do a word search with regex and wonder how to type AND for multiple criteria.
For example, how to type the following:
(Start with a
) AND (Contains p
) AND (Ends with e
), such as the word apple
?
Input
apple
pineapple
avocado
Code
grep -E "regex expression here" input.txt
Desired output
apple
What should the regex expression be?
Solution
In general you can't implement and
in a regexp (but you can implement then
with .*
) but you can in a multi-regexp condition using a tool that supports it.
To address the case of and
s, you should have made your example starts with a and includes p and includes l and ends with e
with input including alpine
so it wasn't trivial to express in a regexp by just putting .*
s in between characters but is trivial in a multi-regexp condition:
$ cat file
apple
pineapple
avocado
alpine
Using &&
s will find both words regardless of the order of p
and l
as desired:
$ awk '/^a/ && /p/ && /l/ && /e$/' file
apple
alpine
but, as you can see, you can't just use .*
s to implement and
:
$ grep '^a.*p.*l.*e$' file
apple
If you had to use a single regexp then you'd have to do something like:
$ grep -E '^a.*(p.*l|l.*p).*e$' file
apple
alpine
Answered By - Ed Morton Answer Checked By - Gilberto Lyons (WPSolving Admin)