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

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



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



  2. 说明:
    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



注意:在windows批处理中,setlocal EnableDelayedExpansion之后,感叹号!字符是变量延迟,必须用^!代替。单引号要改成双引号。

%sed% -i -e "/title\(.*\)!x2!/,/title/{/title/^!d}" %menu%