Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backward search and replace using sed

Tags:

regex

sed

perl

How to search for the last occurrence of a particular word/pattern in a string and replace it with an another word?

For example, Search word is aaa and Replace word is zzz

Input: aaa bbb ccc bbb aaa

Desired Output: aaa bbb ccc bbb zzz

s/aaa/zzz/ replaces first word. Is there any additional option to search reverse?

like image 680
jkshah Avatar asked Sep 26 '13 18:09

jkshah


1 Answers

Using sed:

x='aaa bbb ccc bbb aaa'
sed 's/\(.*\)bbb/\1zzz/' <<< "$x"

aaa bbb ccc zzz aaa

Using perl command line:

sed doesn't support lookarounds so if you want to give perl a chance:

perl -pe 's/aaa(?!.*?aaa)/zzz/' <<< "$x"

aaa bbb ccc bbb zzz
like image 141
anubhava Avatar answered Nov 22 '22 14:11

anubhava