How do I replace only the last occurrence of "-" in a string with a space using sed?

For example:


but I want to get the following output ( replacing the last hyphen [“-“] with a space )

swp-RedHat-Linux-OS- 03

3 Answers 3


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-' | sed 's/\(.*\)-/\1 /'
swp-RedHat-Linux-OS- 03
  • 4
    Note, this is not portable. Some non-GNU versions of sed do not support pattern matches. In that case, you'll need something else, be it perl -pne 's/(.*)-/$1 /' or @Thor's parameter expansion solution or something else.
    – Adam Katz
    Mar 6, 2015 at 22:02
  • of course :-) thx...
    – Greg
    Jul 12, 2016 at 15:42
  • You shouldn't need to escape those brackets when using single quotes.
    – jgmjgm
    Dec 27, 2017 at 12:27
  • @jgmjgm You can omit backslashes by using extended regular expression with sed -r.
    – jimmij
    Dec 27, 2017 at 13:25
  • 1
    @VinayPotluri Try sed -r 's/(.*)-(.*)-/\1 \2 /').
    – jimmij
    May 8, 2018 at 21:00

You could also handle this with bash parameter expansion:

echo ${s%-*} ${s##*-}


swp-RedHat-Linux-OS- 03
  • Very creative, love this answer
    – dpritch
    Nov 14, 2017 at 22:39
  • Hi Thor. Nice trick. I'd like to do this, but on a Bash array. Any ideas? Feb 7, 2021 at 18:49

Something like this worked for me, although I'm sure there are better ways

echo "swp-RedHat-Linux-OS-" | rev | sed 's/-/ /' | rev
swp-RedHat-Linux-OS- 03
  • This is bad...plain bad. Why do 4 operations when you can do 2?
    – Sarima
    Mar 3, 2015 at 14:18
  • 12
    For someone with only a basic understanding of regular expressions, this answers seems much more approachable. And who cares how many operations it takes, this is going to be instantaneous for all practical cases. So I would consider readability over some arbitrary rule to use as few operations as possible.
    – Psirus
    Mar 3, 2015 at 20:38
  • 6
    @Psirus I hope this isn't going to open up a can of worms, but the idea of using lesser operations is to showcase a certain level of mastery of the lesser operations. For example, @Thor's answer shows an appreciation of bash parameter expansion feature, which works well if OP is using bash too. There is going to be a delicate balance between readability (to the point of being very verbose) and using the right tools, but more often than not using the right tools prevails.
    – h.j.k.
    Mar 4, 2015 at 3:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.