grep is very useful tool for text search and pattern matching. We have all ready provided tutorial and examples about
egrep . In this tutorial we will look
not logic operations in detail.
We will use following text during tutorial for
grep operations. This is the wage list of Manchester United Football Team.
David de Gea 26 £200,000 2 Years (2019) Sergio Romero 30 £50,000 4 Years (2021) Marcos Rojo 27 £70,000 2 Years (2019) Phil Jones 25 £50,000 2 Years (2019) Chris Smalling 27 £80,000 2 Years (2019) Eric Bailly 23 £75,000 3 Years (2020)
or logic matches all lines if one of the pattern match. We will use
\| to specify OR logic. In this example we will look players those age
$ grep "23\|30" manchester.txt
OR with Extended Grep
Another way to implement OR logic is using
grep command extended option with
-E. We will specify OR logic with
| . In this example we will look players those age
$ grep -E "23|30" manchester.txt
OR with Egrep
Another tool used to implement OR logic is
egrep. We will use
| operator again. In this example we will look players those age
$ egrep "23|30" manchester.txt
AND logic will match lines those have all provided patterns. We will use
.* for AND operator. In this example we will list players those contract is 2 years and age is 27.
$ grep "27.*2 Years" manchester.txt
AND with Multiple Grep
Another implementation is using multiple grep commands to filter given patterns. In this example we will list players those contract is 2 years and age is 27.
$ grep "2 Years" manchester.txt | grep 27
NOT logic is used to get results those do not matched given pattern. We will use
-v option for grep. In this example we will list players those do not 27 years old.
$ grep -v "27" manchester.txt
NOT with Multiple Grep Conditions
We can implement NOT logic multiple times with multiple
grep commands. We will pipe multiple grep commands in bash. In this example we will list players those is not 27 years old and not have 2 Years contract.
$ grep -v "27" manchester.txt | grep -v "2 Years"