Using sed can you specify the last instance of a character on a line?

I was told a way to do this with awk earlier today but is there a way with sed to specify the last instance of a character on a line?

You will know what character you're looking for but there could be none or one hundred instances of it on a line say and you ONLY want to specify the last one for a substitution.

$ echo 1234512345 | sed "s/\(.*\)3/\1<<X>>/"
1234512<<X>>45
$ echo 1234512345 | sed "s/\(.*\)6/\1<<X>>/"
1234512345
1 Like

Thanks Scott

Could you explain how that's working possibly.

In the pattern .*3 matches all characters up to the character 3. Because sed uses a greedy match, it matches all characters up to the last three.

Adding the parens \(.*\)3 'groups' the part of the input string that was matched by the enclosed pattern. In this case, all characters before the 3.

In the replacement string, the \1 is a 'back reference' to the first group, so what ever was matched by the first group is 'kept' in the output string. The remainder of the substitution string is then added.

Because the text following the last occurrence of the desired character is NOT matched, it is left alone in the replacement process and appears as it was in the input string.

I hope this makes sense.

1 Like