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
Regex to replace last occurrence of a string in each line
提问by Michael
I am using sed -e 's/\(.*\)ABC/\1DEF/' myfile
to replace the last occurrence of ABC
with DEF
in a file.
我sed -e 's/\(.*\)ABC/\1DEF/' myfile
用来替换文件中最后一次出现的ABC
with DEF
。
I want to modify it to replace the last occurrence of ABC
with DEF
in each linein the file.
我想修改它以替换文件中每一行中最后一次出现的ABC
with 。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'