简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM