How do I replace the last occurrence of a character in a string using sed?
You can do it with single sed
:
sed 's/\(.*\)-/\1 /'
or, using extended regular expression:
sed -r 's/(.*)-/\1 /'
The point is that sed
is very greedy, so matches as many characters before -
as possible, including others -
.
$ echo 'swp-RedHat-Linux-OS-5.5.0.0-03' | sed 's/\(.*\)-/\1 /'
swp-RedHat-Linux-OS-5.5.0.0 03
You could also handle this with bash parameter expansion:
s=swp-RedHat-Linux-OS-5.5.0.0-03
echo ${s%-*} ${s##*-}
Output:
swp-RedHat-Linux-OS-5.5.0.0 03
Something like this worked for me, although I'm sure there are better ways
echo "swp-RedHat-Linux-OS-5.5.0.0-03" | rev | sed 's/-/ /' | rev
swp-RedHat-Linux-OS-5.5.0.0 03