Grep “OR” Condition Tutorial

The grep command is used to filter or search or match some text or regex in a text file. The grep command provides a lot of different options and features that can be used for different cases. The grep command can be used to match one of the multiple search terms which can be accomplished with the OR logic. The OR logic is used to match one of the provided search terms. In this tutorial, we examine how to use the OR condition.

OR Condition without Option

The most basic implementation for the grep OR condition is using the \| characters like below.

grep "PATTERN1\|PATTERN2\|PATTERN3" FILE
  • PATTERN1,PATTERN2 and PATTERN3 are the search terms or patterns we want to match.
  • \| characters are used to make OR condition and put between search terms or patterns.
  • FILE is the file we search.

In the following example, we match one of “ferrari”,”opel”,”audi”.

$ grep "ferrari\|opel\|audi" cars.txt

OR Condition with -E Option

The grep command OR condition can be enabled with the -E option like below.

grep -E "PATTERN1|PATTERN2|PATTERN3" FILE
  • PATTERN1,PATTERN2 and PATTERN3 are the search terms or patterns we want to match.
  • -E option is used to make search term with OR condition.
  • | character is used for OR condition

In the following example, we match one of “ferrari”,”opel”,”audi”.

$ grep -E "ferrari|opel|audi" cars.txt

OR Condition with -e Options

Another way to create OR condition with grep command is using the -e option. For every OR condition the -e option is used once and the pattern or search term is added.

grep -e PATTERN1 -e PATTERN2 -e PATTERN3 FILE
  • PATTERN1,PATTERN2 and PATTERN3 are the search terms or patterns we want to match.
  • -e option is used to specify every condition. The -e option is used multiple times to specify multiple OR conditions.

In the following example, we match one of “ferrari”,”opel”,”audi”.

$ grep -e "ferrari" -e "opel" -e "audi" cars.txt

egrep Command OR Condition

The egrep command is a bit extended implementation of the grep command. The egrep command is the same as “grep -E”.

egrep "PATTERN1|PATTERN2|PATTERN3" FILE
  • egrep command is extended version of the grep command and provides the -e and -E options automatically by default.
  • PATTERN1,PATTERN2 and PATTERN3 are the search terms or patterns we want to match.
  • | character is used to implement OR conditions.

In the following example, we match one of “ferrari”,”opel”,”audi”.

$ grep -E "ferrari|opel|audi" cars.txt

Leave a Comment