So I have the following 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
I want to replace the last space just before the numbers with a hyphen, this is the closest I've got
cat file.txt | sed -r 's/\ /\-/g'
But this replaces all spaces with a - I want the output to look like this:
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
Any ideas?
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
Here is an awk
variation:
awk '{$NF="-"$NF;sub(/ -/,"-")}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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With