Shell Script(sed)多行匹配问题

2017-04-16 17:51:37 +08:00
 funagi

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,查了资料说可以用跳转标记匹配多行,但我一脸懵逼没看懂用法。

2358 次点击
所在节点   Bash
8 条回复
fangxing204
2017-04-16 18:31:46 +08:00
sed 是面向“行”的编辑器
yangg
2017-04-16 19:33:46 +08:00
sed 专门干这事的!!!
使用函数 a
sed "/match_reg/a added content" -i hosts

参考: https://uedsky.com/2016-10/sed-awk/#sed-tutorial
funagi
2017-04-17 19:15:28 +08:00
@yangg 函数 a 用法看懂了,但好像没法实现我想要的效果
yangg
2017-04-17 19:51:05 +08:00
不是在行下面插入内容么?什么系统?
funagi
2017-04-17 20:38:44 +08:00
@yangg Debian ,是在行上面插内容,而且还是跨行的。
yangg
2017-04-17 21:06:05 +08:00
跨行什么意思,示例没看出来
funagi
2017-04-17 21:20:44 +08:00
@yangg “# The following lines are desirable for IPv6 capable hosts ”这一行上面不是有一空行吗,将这两行视为一个整体块区,在这块区的上面插入内容
funagi
2017-04-19 22:34:56 +08:00
@yangg 重新看了你提供的参考,用`sed 'N;/# The following/i content' hosts`基本上解决了问题,虽然没法确认 N 是不是空行 ,非常感谢。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/355226

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX