首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >‘'sed’:如何在字符串匹配+2行之后添加新行

‘'sed’:如何在字符串匹配+2行之后添加新行
EN

Stack Overflow用户
提问于 2013-04-25 20:29:54
回答 4查看 17.1K关注 0票数 8

我想在字符串匹配+2行之后添加一个新行。

这是我的文件:

代码语言:javascript
复制
allow-hotplug eth0
auto eth0
iface eth0 inet static
address 172.16.2.245
netmask 255.255.254.0
gateway 192.168.1.1

allow-hotplug eth1
#auto eth1
iface eth1 inet static
address 192.168.0.240
netmask 255.255.255.0

iface eth2 inet static
address 192.168.2.240
netmask 255.255.255.0

我想在找到'iface eth1‘+2行之后添加'gateway 192.168.1.1’。

示例:执行sed命令后需要获取的内容

代码语言:javascript
复制
allow-hotplug eth0
auto eth0
iface eth0 inet static
address 172.16.2.245
netmask 255.255.254.0
gateway 172.16.2.254

allow-hotplug eth1
#auto eth1
iface eth1 inet static
address 192.168.0.240
netmask 255.255.255.0
gateway 192.168.1.1

iface eth2 inet static
address 192.168.2.240
netmask 255.255.255.0

我知道如何找到并移动2行后,在特定字符串后追加行,等等,但不结合这2个操作。斯蒂芬

EN

回答 4

Stack Overflow用户

发布于 2013-04-25 21:00:49

这似乎起作用了:

代码语言:javascript
复制
sed '/^iface eth1/{N;N;s/$/\ngateway 192.168.1.1/}' input.txt

-i选项添加到sed以将结果保存回input.txt

票数 11
EN

Stack Overflow用户

发布于 2013-04-25 21:04:13

使用sed的一种方式

代码语言:javascript
复制
sed '
/iface eth1/ {
n
n
a\gateway 192.168.1.1
}' file
票数 4
EN

Stack Overflow用户

发布于 2013-04-25 21:10:32

您要求使用' sed‘,但'Kent’使用的是'awk',这里有一个sed脚本,它可以为您的示例执行您想要的操作。更一般地说,sed脚本的第1行可以包含您想要的任何字符串,sed脚本的第5行可以包含您想要的任何字符串。将以下脚本放入一个文件中,比如x.sed,不要添加任何空格或制表符。

代码语言:javascript
复制
    /iface eth1/{
    n
    n
    a\
    gateway 192.168.1.1
    }

然后在命令行上像这样运行它。

代码语言:javascript
复制
    sed -f x.sed "myinputfile" > "myoutputfile"
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16214828

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档