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

Updated:   |  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 Buy Me A Coffee



Comments


Add a Comment


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