How to Use OR Operator in sed Regex


Often you may want to use the OR operator in sed to replace multiple patterns using regex.

You can use the following basic syntax to do so:

sed -e 's/\(Mavs\|Mavericks\)-.*/Lakers/g' team_points.txt

This particular example makes the following replacements in the file named team_points.txt:

  • Replace all occurrences of Mavs- followed by any characters with Lakers
  • Replace all occurrences of Mavericks- followed by any characters with Lakers

Note that we use the | operator to represent “OR” logic and we use a backslash immediately before it to escape it.

Here is what the various sed commands do:

  • -e: Specifies that the string following it should be interpreted as an extended regular expression
  • s: Used to “substitute” one pattern for another
  • g: Used to make substitutions “globally”, i.e. for all occurrences

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

Example: How to Use OR Operator in sed Regex

Suppose that we have a file named team_points.txt that contains information about points scored by basketball players on various teams.

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

The first column contains the team name and the second column contains the points scored by the player.

Suppose that we would like to replace each occurrence of “Mavs-” followed by anything and “Mavericks-” followed by anything with “Lakers” instead.

We can use the following syntax to do so:

sed -e 's/\(Mavs\|Mavericks\)-.*/Lakers/g' team_points.txt

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

sed regex or

Notice that each of the patterns that we specified have been replaced by “Lakers” instead.

Related Tutorials

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

How to Use Case-Insensitive Search and Replace in sed
How to Use sed to Replace newline with space
How to Use sed to Replace All Occurrences of Pattern
How to Use sed to Replace All Text Before Match

Leave a Reply