Bash (Scripting) - do something first all or last match

by
Jeremy Canfield |
Updated: November 30 2021
| Bash (Scripting) articles
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
This sed statement will replace only the first occurrence of "Hello" with "Goodbye".
~]# echo "Hello John Hello Amy Hello Sal" | sed "s|Hello|Goodbye|"
Goodbye John Hello Amy Hello Sal
The g (global) flag can be used to replace every occurrence of "Hello" with "Goodbye".
~]# echo "Hello John Hello Amy Hello Sal" | sed "s|Hello|Goodbye|g"
Goodbye John Goodbye Amy Goodbye Sal
The following can be used to only replace the last occurrence of "Hello" with "Goodbye".
~]# echo "Hello John Hello Amy Hello Sal" | sed "s|\(.*\)Hello|\1Goodbye|"
Hello John Hello Amy Goodbye Sal
Did you find this article helpful?
If so, consider buying me a coffee over at