How to use logical operators (OR, AND & NOT) with Linux grep command

Linux grep is one of the most used commands by system administrators, computer programmers and ethical hackers. This article will see How to use logical operators (OR, AND, NOT) with Linux grep command. Linux grep command is used to filter information based on pattern matching. Suppose you have logs of the firewall, and you want to search for specific IPs. Linux grep command comes for rescue, and you can use the logical operators' functionality of this command. Click Here if you are interested in understanding Top Linux Commands for Beginners.

Click Here if you are interested in Learning Linux Fundamentals

We will use the below data to demonstrate logical AND, OR, and NOT operators in grep:

(1) Use '\|' for using OR in grep

Below commands print lines that match pattern1 or pattern2 till pattern n

cat <file> | grep '<pattern1>\|<pattern2>\|....<patternn>'

or

grep '<pattern1>\|<pattern2>\|....<patternn>' <file>

(2) Use -E option for using OR in grep

Below commands print lines that match pattern1 or pattern2 till pattern n by using -E option

cat <file> | grep -E '<pattern1>|<pattern2>|....<patternn>'

or

grep '<pattern1>|<pattern2>|....<patternn>' <file>

(3) Use -v option for using the NOT operator in grep

Below commands print lines that not matches pattern1

cat <file> | grep -v '<pattern1>'

or

grep -v '<pattern1>' <file>

(4) AND operator usage example in grep by using multiple patterns

Below commands print lines that matches pattern1, pattern 2 and pattern 3

cat <file> | grep 'pattern1' | grep 'pattern2' | grep 'pattern3'

or

grep <pattern1> <file> | grep <pattern2> | grep <pattern3>

(5) AND operator implement using -E option

Below commands print lines that match pattern1 and pattern2

grep -E '{pattern1}.{pattern2}|{pattern2}.{pattern1}' {file}

Conclusion

Linux grep command is awesome in pattern matching only if you know it very well. In this article, we have covered How to use logical operators (OR, AND & NOT) with Linux grep command.

Subscribe us to receive more such articles updates in your email.

If you have any questions, feel free to ask in the comments section below. Nothing gives me greater joy than helping my readers!

Disclaimer: This tutorial is for educational purpose only. Individual is solely responsible for any illegal act.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

10 Blockchain Security Vulnerabilities OWASP API Top 10 - 2023 7 Facts You Should Know About WormGPT OWASP Top 10 for Large Language Models (LLMs) Applications Top 10 Blockchain Security Issues