V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
funagi
V2EX  ›  Bash

Shell Script(sed)多行匹配问题

  •  
  •   funagi · 2017-04-16 17:51:37 +08:00 · 2354 次点击
    这是一个创建于 2566 天前的主题,其中的信息可能已经有所发展或是发生改变。

    hosts 文件内容

    127.0.0.1       localhost
    127.0.1.1       exmaple-some.com
    
    # The following lines are desirable for IPv6 capable hosts
    ::1     localhost ip6-localhost ip6-loopback
    ff02::1 ip6-allnodes
    ff02::2 ip6-allrouters
    

    使用脚本

    add-host() {
      sed -i "/^# The following/i\\${1}" hosts
    }
    
    add-host '127.0.1.1       a.newdomain.com'
    add-host '127.0.1.1       b.newdomain.com'
    

    期望结果

    127.0.0.1       localhost
    127.0.1.1       exmaple-some.com
    127.0.1.1       a.newdomain.com
    127.0.1.1       b.newdomain.com
    
    # The following lines are desirable for IPv6 capable hosts
    ::1     localhost ip6-localhost ip6-loopback
    ff02::1 ip6-allnodes
    ff02::2 ip6-allrouters
    

    实际结果

    127.0.0.1       localhost
    127.0.1.1       exmaple-some.com
    
    127.0.1.1       a.newdomain.com
    127.0.1.1       b.newdomain.com
    # The following lines are desirable for IPv6 capable hosts
    ::1     localhost ip6-localhost ip6-loopback
    ff02::1 ip6-allnodes
    ff02::2 ip6-allrouters
    

    exmaple-some.com 所在行实际内容不定,所以无法匹配这行再往下插入。

    sed 一般是对行进行处理,所以无法匹配\n# The following,查了资料说可以用跳转标记匹配多行,但我一脸懵逼没看懂用法。

    第 1 条附言  ·  2017-04-16 19:30:05 +08:00
    能用 sed 解决当然是最好的,不用 sed 也可以,只要是 Shell Script 就行。
    8 条回复    2017-04-19 22:34:56 +08:00
    fangxing204
        1
    fangxing204  
       2017-04-16 18:31:46 +08:00 via Android
    sed 是面向“行”的编辑器
    yangg
        2
    yangg  
       2017-04-16 19:33:46 +08:00   ❤️ 1
    sed 专门干这事的!!!
    使用函数 a
    sed "/match_reg/a added content" -i hosts

    参考: https://uedsky.com/2016-10/sed-awk/#sed-tutorial
    funagi
        3
    funagi  
    OP
       2017-04-17 19:15:28 +08:00
    @yangg 函数 a 用法看懂了,但好像没法实现我想要的效果
    yangg
        4
    yangg  
       2017-04-17 19:51:05 +08:00 via iPhone
    不是在行下面插入内容么?什么系统?
    funagi
        5
    funagi  
    OP
       2017-04-17 20:38:44 +08:00
    @yangg Debian ,是在行上面插内容,而且还是跨行的。
    yangg
        6
    yangg  
       2017-04-17 21:06:05 +08:00 via iPhone
    跨行什么意思,示例没看出来
    funagi
        7
    funagi  
    OP
       2017-04-17 21:20:44 +08:00
    @yangg “# The following lines are desirable for IPv6 capable hosts ”这一行上面不是有一空行吗,将这两行视为一个整体块区,在这块区的上面插入内容
    funagi
        8
    funagi  
    OP
       2017-04-19 22:34:56 +08:00
    @yangg 重新看了你提供的参考,用`sed 'N;/# The following/i content' hosts`基本上解决了问题,虽然没法确认 N 是不是空行 ,非常感谢。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5733 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 06:25 · PVG 14:25 · LAX 23:25 · JFK 02:25
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.