Sed - 替换每行最后出现的匹配项 [英] Sed - Replace last occurrence of match for each line

查看:89
本文介绍了Sed - 替换每行最后出现的匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有以下文件:

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

有什么想法吗?

推荐答案

这个怎么样?

$ 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

  • ([^ ]*)$ 捕获空格+任何不是行尾的空格".
  • -\1 打印连字符 + 捕获的任何不是行尾的空格".
    • ([^ ]*)$ 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".
    • 这篇关于Sed - 替换每行最后出现的匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆