Linux Grep OR, AND, NOT Operator and Logic Examples – POFTUT

Linux Grep OR, AND, NOT Operator and Logic Examples


logrep is very useful tool for text search and pattern matching. We have all ready provided tutorial and examples about grep and egrep . In this tutorial we will look grep command or , and , not logic operations in detail.

Example Text

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

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 23 OR 30.

$ grep "23\|30" manchester.txt
OR Logic
OR Logic

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 23 OR 30.

$ grep -E "23|30" manchester.txt
OR with Extended Grep
OR with Extended Grep

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 23 OR 30.

$ egrep "23|30" manchester.txt
OR with Egrep
OR with Egrep

AND Logic

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 Logic
AND Logic

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
AND with Multiple Grep
AND with Multiple Grep

NOT Logic

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 Logic
NOT Logic

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"
NOT with Multiple Grep Conditions
NOT with Multiple Grep Conditions

LEARN MORE  Linux egrep Command Tutorial with Examples

Leave a Comment