正则表达式替换每行中最后一次出现的字符串 [英] Regex to replace last occurrence of a string in each line

查看:39
本文介绍了正则表达式替换每行中最后一次出现的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 sed -e's/\(.* \)ABC/\ 1DEF/'myfile 将上一次出现的 ABC 替换为文件中的DEF .

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

我想对其进行修改,以将文件每行中的 DEF 替换为最后一次出现的 ABC .

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 ?

谢谢

推荐答案

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

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

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

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

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

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

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'

这篇关于正则表达式替换每行中最后一次出现的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆