Do something for last occurrence using SED in Linux Bash

Home > Search

Let's say you have two or more identical strings of data. In this example, the text "Hello" is found more than once.

Hello John Hello Amy Hello Sal

A simple sed statement will replace every occurrence of the world "Hello". 

~]# echo "Hello John Hello Amy Hello Sal" | sed "s|Hello|Goodbye|"
Goodbye John Goodbye Amy Goodbye Sal


The following sed statement can be used to only replace the last occurrence of "Hello".

~]# echo "Hello John Hello Amy Hello Sal" | sed "s|\(.*\)Hello|\1Goodbye|"
Hello John Hello Amy Goodbye Sal


Add a Comment

We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.

Please enter in the box below so that we can be sure you are a human.