How to exclude part of matching string from replacement?

Viewed 74

Let's say that I want to change all words ending with -et so that they instead end with -ert

Just doing a simple sed 's/et /ert /g' would work for all words followed by another word. But only if it is followed by a space. It can also be followed by '.', ',', ':' or other characters. Running sed for every individual case does not seem to be the correct way.

What I'm looking for is something like "for every match of AB, replace A with C, but don't touch B".

Clarification due to comments:

It's not limited to the ending of the words. I would like to do this inside words as well. Like:

$ echo "aaetxaa" | sed '?'
aaertxaa
$ echo "aaetyaa" | sed '?'
aaetyaa

So the replacement only took place when the matching ended with an x and not a y.

1 Answers

I assume that you want to match et only if it is followed with x or end of string.

In this case, you may use

sed -E 's/et(x|$)/ert\1/g'

See the online sed demo:

echo "aaetxaa" | sed -E 's/et(x|$)/ert\1/g'
# => aaertxaa
echo "aaetyaa" | sed -E 's/et(x|$)/ert\1/g'
# => aaetyaa

Details

  • -E - POSIX ERE syntax enabled
  • s/ - substitution command, / is the delimiter
  • et(x|$) - LHS: et followed with either x or end of string captured into Group 1
  • ert\1 - ert and the value of Group 1
  • g - global flag: match and replace all occurrences on a line.
Related