Unix & Linux: How do I replace the last occurrence of a character in a string using sed?
Channel: Roel Van de Paar
Date: 2020-08-14

Unix & Linux: How do I replace the last occurrence of a character in a string using sed?


The Question: How do I replace only the last occurrence of "-" in a string with a space using
sed?
For example:
echo $MASTER_DISK_RELEASE
swp-RedHat-Linux-OS-5.5.0.0-03
but I want to get the following output ( replacing the last hyphen ["-"] with a
space )
swp-RedHat-Linux-OS-5.5.0.0 03

Solutions: Please watch the whole video to see all solutions, in order of how many people found them helpful

== This solution helped 11 people ==
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

== This solution helped 52 people ==
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

With thanks & praise to God, and with thanks to the many people who have made this project possible! | Content (except music & images) licensed under cc by-sa 3.0 | Music: https://www.bensound.com/royalty-free-music | Images: https://stocksnap.io/license & others | With thanks to user ??s??? (https://unix.stackexchange.com/users/72456), user Thor (https://unix.stackexchange.com/users/17666), user rahul (https://unix.stackexchange.com/users/73825), user maihabunash (https://unix.stackexchange.com/users/67059), user jimmij (https://unix.stackexchange.com/users/80886), and the Stack Exchange Network (http://unix.stackexchange.com/questions/187889). Trademarks are property of their respective owners. Disclaimer: All information is provided "AS IS" without warranty of any kind. You are responsible for your own actions. Please contact me if anything is amiss at Roel D.OT VandePaar A.T gmail.com.