Bash: Use Regex with “OR” to Match Multiple Patterns


Often you may want to use Regular Expressions in Bash with “OR” logic to match one or more patterns.

You can use the following syntax to do so:

grep -E 'A00|C00' employees.txt

This particular example will return all lines in the file named employees.txt that contain “A00” or “C00” somewhere in the line.

Note that the -E operator specifies that you’re using an extended regular expression and the | operator is used to represent “OR” logic.

The following example shows how to use this syntax in practice.

Example: Use Regex with “OR” to Match Multiple Patterns in Bash

Suppose that we have a text file named employees.txt that contains employee ID values for various employees at some company.

We can use the cat command to view the contents of this file:

Suppose that we would like to return only the lines from the file that contain either “A00” or “C00” somewhere in the line.

We can use the following syntax to do so:

grep -E 'A00|C00' employees.txt

The following screenshot shows how to use this syntax in practice:

Bash Regex OR

Notice that this returns only the lines from the file that contain either “A00” or “C00” somewhere in the line.

Note that we must use the -E operator after the grep command to ensure that the string that the follows it is interpreted as an extended regular expression.

If we don’t include the -E operator then grep will attempt to find the literal string ‘A00|C00’ instead.

Note: We used one | operator to search for two possible patterns but you can use as many | operators as you’d like to search for even more patterns.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Filter CSV File Based on Column Value
Bash: How to Extract Specific Columns from CSV File
Bash: How to Use find -exec with grep

Leave a Reply