使用sed删除或操作两个pattern模式匹配行之间的内容

使用sed删除两个模式匹配行之间的内容

在配置文件中有时候想要把两节之间的内容全部删除,便于修改为新的配置,sed命令如下

//删除模式匹配行之间的内容
sed -i  '/\[section1\]/,/\[section2\]/{/\[section1\]/!{/\[section2\]/!d}}'   test.repo

 

说明:
1. 中括号需要用转义运算符。 \[section1\]
2. /string1/!,其中的!表示行中没有匹配到string1。
3. /[section1]/,/[section2]/为行定位,选择在小节[section1]到[section2]之间的行,包含[section1]和[section2]这两行。
4. {/[section1]/!{/[section2]/!d}}为之前定位后的操作,需要排除掉[section1]和[section2]这两行,使用/[section1]/!来排除掉[section1]这一行,使用{/[section2]/!d}}继续排除掉[section2]这一行,然后执行删除操作。

 

 

示例:

 

//删除模式匹配行之间的内容
[root@localhost backup]# cat test.repo
# CentOS-Base.repo
[base]
name=CentOS-$releasever - Base
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os&infra=$infra
#baseurl=http://mirror.centos.org/centos/$releasever/os/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
[updates]
name=CentOS-$releasever - Updates
[root@localhost backup]# sed   '/\[base\]/,/\[updates\]/{/\[base\]/!{/\[updates\]/!d}}'   test.repo                            
# CentOS-Base.repo
[base]
[updates]
name=CentOS-$releasever - Updates

 

 

使用sed操作两个模式行之间的内容


基于sed定位两个模式匹配行之间内容的方法
‘/[section1]/,/[section2]/{/[section1]/!{/[section2]/!d}}’
将d命令修改为相应的命令集合即可,例如
‘/[section1]/,/[section2]/{/[section1]/!{/[section2]/!{s/string1/string2/g;…;}}}’
 

 

 

//操作模式匹配行之间的内容
sed -i  '/\[section1\]/,/\[section2\]/{/\[section1\]/!{/\[section2\]/!{s/string1/string2/g;...;}}}'   test.repo

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值