Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to replace last occurrence of a string in each line

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

like image 861
Michael Avatar asked Jun 07 '11 20:06

Michael


People also ask

How do you replace the last occurrence of a character in a string?

To replace the last occurrence of a character in a string: Use the lastIndexOf() method to get the last index of the character. Call the substring() method twice, to get the parts of the string before and after the character to be replaced. Add the replacement character between the two calls to the substring method.

How does .replace work in regex?

The replace() method returns a new string with one, some, or all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced.

How do I replace a word in a string in regex?

To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring. The string 3foobar4 matches the regex /\d. *\d/ , so it is replaced.

Does string replace take regex?

The Regex. Replace(String, MatchEvaluator, Int32, Int32) method is useful for replacing a regular expression match if any of the following conditions is true: The replacement string cannot readily be specified by a regular expression replacement pattern.


1 Answers

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'
like image 147
Bacon Avatar answered Sep 21 '22 12:09

Bacon