Regex to replace last occurrence of a string in each line

后端 未结 1 1659
孤街浪徒
孤街浪徒 2021-02-14 03:58

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

1条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-14 04:44

    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 讨论(0)
提交回复
热议问题