Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sed - Replace last occurrence of match for each line

Tags:

regex

sed

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?

like image 853
bk201 Avatar asked Apr 04 '14 11:04

bk201


4 Answers

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".
like image 125
fedorqui 'SO stop harming' Avatar answered Nov 05 '22 23:11

fedorqui 'SO stop harming'


You know how to replace the first space, right?

rev inputfile | sed 's/ /-/' | rev
like image 38
choroba Avatar answered Nov 05 '22 22:11

choroba


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
like image 6
devnull Avatar answered Nov 05 '22 21:11

devnull


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
like image 4
Jotne Avatar answered Nov 05 '22 22:11

Jotne