29

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
44

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
  • 2
    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 '15 at 22:02
  • of course :-) thx... – Greg Jul 12 '16 at 15:42
  • You shouldn't need to escape those brackets when using single quotes. – jgmjgm Dec 27 '17 at 12:27
  • @jgmjgm You can omit backslashes by using extended regular expression with sed -r. – jimmij Dec 27 '17 at 13:25
  • 1
    @VinayPotluri Try sed -r 's/(.*)-(.*)-/\1 \2 /'). – jimmij May 8 '18 at 21:00
26

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
  • Very creative, love this answer – dpritch Nov 14 '17 at 22:39
11

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 is bad...plain bad. Why do 4 operations when you can do 2? – Joshpbarron Mar 3 '15 at 14:18
  • 6
    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 '15 at 20:38
  • 4
    @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 '15 at 3:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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