开发者

Regex to replace last occurrence of a string in each line

开发者 https://www.devze.com 2023-03-10 22:14 出处:网络
I am using sed -e \'s/\\(.*\\)ABC/\\1DEF/\' myfile to replace the last occurrence of ABC with DEF in a file.

I am using sed -e 's/\(.*\)ABC/\1DEF/' myfile to replace the last occurrence of ABC with DEF in a file.

I want to modify it to replace the last occurren开发者_高级运维ce of ABC with DEF in each line in the file.

Is it possible to do with regex ?

Thanks


You need to add 'g' to the end of your sed:

sed -e 's/\(.*\)ABC/\1DEF/g'

This tells sed to replace every occurrence of your regex ("globally") instead of only the first occurrence.

EDIT: You should also add a $, if you want to ensure that it is replacing the last occurrence of ABC on the line:

sed -e 's/\(.*\)ABC$/\1DEF/g'
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号