How to Use sed to Replace Last Occurrence of Character in String


Often you may want to use sed to replace the last occurrence of a specific character or specific pattern in a string.

You can use the following basic syntax to do so:

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

This particular example replaces the last occurrence of the string “this” with the string “that” in the variable named $my_string.

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

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

Example: Use sed to Replace Last Occurrence of Character in String

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

  • A003EmployeeGreg

And suppose that we would like to replace the last “e” in the string with an underscore so that we are left with the following:

  • A003EmployeeGr_g

We can use the following syntax to do so:

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

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

sed replace last occurrence in string

Notice that this returns A003EmployeeGr_g, which represents the original string with the last “e” character replaced by an underscore.

Note that you can replace the last occurrence of the “e” with any pattern you would like.

For example, you could use the following syntax to replace the last “e” with the string “LAST” instead:

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

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

Notice that this returns A003EmployeeGrLASTg, which represents the original string with the last “e” character replaced by the string “LAST” instead.

Related Tutorials

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

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 After Match

Leave a Reply