jkshah
jkshah

Reputation: 11713

Backward search and replace using sed

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

Answers (2)

paratrooper
paratrooper

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

anubhava
anubhava

Reputation: 786101

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

Upvotes: 5

Related Questions