How do I replace the last occurrence of a character in a string using sed?

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

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

Method 3

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x