Sed - Replace last occurrence of match for each line

What about this?

$ sed -r 's/ ([^ ]*)$/-\1/' file
Carlton-3053
Carlton North-3054
Docklands-3008
East Melbourne-3002
Flemington-3031
Kensington-3031
Melbourne-3000
Melbourne-3004
North Melbourne-3051
St Kilda East-3183
  • ([^ ]*)$ catches space + "anything not being a space up to the end of line".
  • -\1 print hyphen + the catched "anything not being a space up to the end of line".

You know how to replace the first space, right?

rev inputfile | sed 's/ /-/' | rev

Your attempt was close. You just needed to capture everything before the space and needed a backslash reference in the replacement. Not sure why you escaped the space and hyphen, though.

sed -r 's/(.*) /\1-/g' inputfile

For your input, it produces:

Carlton-3053
Carlton North-3054
Docklands-3008
East Melbourne-3002
Flemington-3031
Kensington-3031
Melbourne-3000
Melbourne-3004
North Melbourne-3051
St Kilda East-3183

Tags:

Regex

Sed