[英]Sed - Replace last occurrence of match for each line
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". -\\1
打印连字符+捕获的“任何不是直到行尾的空格”。 你知道如何更换第一个空间,对吗?
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
变种:
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
以下也适用于OSX,因为sed -r
在那里不可用:
sed 's/\(.*\) /\1-/' file_containing_your_text.txt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.