Regex to replace last occurrence of a string in each line

社会主义新天地 提交于 2020-01-01 04:30:08

问题


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 occurrence of ABC with DEF in each line in the file.

Is it possible to do with regex ?

Thanks


回答1:


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'


来源:https://stackoverflow.com/questions/6271348/regex-to-replace-last-occurrence-of-a-string-in-each-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!