How to Use sed to Replace All Text Before Match


Often you may want to use sed to replace all text that occurs before a particular pattern in a string.

You can use the methods to do so:

Method 1: Replace All Text Before and Including Pattern

echo $my_string | sed 's/.*Employee//'

This particular example replaces all text before and including the pattern “Employee” in the string variable named $my_string with nothing.

Method 2: Replace All Text Before Pattern

echo $my_string | sed 's/.*\(Employee\)/\1/'

This particular example replaces all text before the pattern “Employee” in the string variable named $my_string with nothing.

Note that we use the s operator in sed in both methods to “substitute” one pattern for another pattern.

The following example shows how to use each method in practice.

Example 1: Use sed to Replace All Text Before and Including Pattern

Suppose that we have the following string that represents an employee ID:

  • A003EmployeeGreg

And suppose that we would like to remove all of the text that occurs before and including “Employee” in the string so that we are left with the following:

  • Greg

We can use the following syntax to do so:

my_string="A003EmployeeGreg"
echo $my_string | sed 's/.*Employee//'

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

sed replace all text before and including pattern

Notice that this returns Greg, which represents the original string with all text before and including “Employee” removed.

Example 2: Use sed to Replace All Text Before Pattern

Suppose that we have the following string that represents an employee ID:

  • A003EmployeeGreg

And suppose that we would like to remove all of the text that occurs before “Employee” in the string so that we are left with the following:

  • EmployeeGreg

We can use the following syntax to do so:

my_string="A003EmployeeGreg"
echo $my_string | sed 's/.*\(Employee\)/\1/'

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

sed replace text before match

Notice that this returns EmployeeGreg, which represents the original string with all text before “Employee” removed.

Feel free to replace “Employee” with whatever pattern you would like to search for in your own string.

Related Tutorials

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

How to Use sed to Replace newline with space
How to Use sed to Replace newline with comma
How to Use sed to Replace All Occurrences of Pattern

Leave a Reply