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
例如,搜索词是aaa,替换词是zzz
Input: aaa bbb ccc bbb aaa
输入:aaa bbb ccc bbb aaa
Desired Output: aaa bbb ccc bbb zzz
期望的输出:aaa bbb ccc bbb zzz
s/aaa/zzz/
replaces first word. Is there any additional option to search reverse?
s / aaa / zzz /替换第一个单词。有没有其他选项可以反向搜索?
2 个解决方案
#1
3
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:
sed不支持lookarounds所以如果你想给perl一个机会:
perl -pe 's/aaa(?!.*?aaa)/zzz/' <<< "$x"
aaa bbb ccc bbb zzz
#2
0
What if we reverse the string, change the FIRST occurrence in reversed string by sed, then reverse the result back to normal order:
如果我们反转字符串,用sed更改反向字符串中的FIRST事件,然后将结果反转回正常顺序怎么办:
#!/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.
如果我们需要替换一个符号,它工作正常。对于单词,您需要反转单词,模式和替换单词。
#1
3
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:
sed不支持lookarounds所以如果你想给perl一个机会:
perl -pe 's/aaa(?!.*?aaa)/zzz/' <<< "$x"
aaa bbb ccc bbb zzz
#2
0
What if we reverse the string, change the FIRST occurrence in reversed string by sed, then reverse the result back to normal order:
如果我们反转字符串,用sed更改反向字符串中的FIRST事件,然后将结果反转回正常顺序怎么办:
#!/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.
如果我们需要替换一个符号,它工作正常。对于单词,您需要反转单词,模式和替换单词。