Reputation: 11713
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?
Upvotes: 5
Views: 8304
Reputation: 61
What if we reverse the string, change the FIRST occurrence in reversed string by sed, then reverse the result back to normal order:
#!/bin/bash
str="aaa bbb ccc bbb aaa"
echo "${str}" | rev | sed 's/bbb/zzz/' | rev
It works fine, if we need to replace just one symbol. For words, you need to reverse both, pattern and replacement words.
Upvotes: 1
Reputation: 786101
x='aaa bbb ccc bbb aaa'
sed 's/\(.*\)bbb/\1zzz/' <<< "$x"
aaa bbb ccc zzz aaa
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
Upvotes: 5