How to Use sed to Replace All Text After Match


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

You can use the methods to do so:

Method 1: Replace All Text After and Including Pattern

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

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

Method 2: Replace All Text After Pattern

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

This particular example replaces all text after 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 After 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 after and including “Employee” in the string so that we are left with the following:

  • A003

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 text after match

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

Example 2: Use sed to Replace All Text After Pattern

Once again, 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 after “Employee” in the string so that we are left with the following:

  • A003Employee

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 all text after specific pattern

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

Feel free to replace “Employee” with whatever specific pattern you would like 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
How to Use sed to Replace All Text Before Match

Leave a Reply