Linux 正则表达式替换每行中最后一次出现的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6271348/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 04:23:46  来源:igfitidea点击:

Regex to replace last occurrence of a string in each line

regexlinuxshellscriptingsed

提问by Michael

I am using sed -e 's/\(.*\)ABC/\1DEF/' myfileto replace the last occurrence of ABCwith DEFin a file.

sed -e 's/\(.*\)ABC/\1DEF/' myfile用来替换文件中最后一次出现的ABCwith DEF

I want to modify it to replace the last occurrence of ABCwith DEFin each linein the file.

我想修改它以替换文件中每一行中最后一次出现的ABCwith 。DEF

Is it possible to do with regex ?

是否可以使用正则表达式?

Thanks

谢谢

采纳答案by Bacon

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

您需要在 sed 的末尾添加“g”:

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

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

这告诉 sed 替换每次出现的正则表达式(“全局”)而不是仅第一次出现。

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

编辑:$如果您想确保它替换行上最后一次出现的 ABC,您还应该添加一个:

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