https://blog.csdn.net/weixin_39833509/article/details/104822701
使用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
注意:在windows批处理中,setlocal EnableDelayedExpansion之后,感叹号!字符是变量延迟,必须用^!代替。单引号要改成双引号。
%sed% -i -e "/title\(.*\)!x2!/,/title/{/title/^!d}" %menu%
sed -e "/title a1/{:a;$^!N;/\ntitle/^!{s/\n\(.*\)//;ta};/title/^!P;D}" -i test.txt
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
2016-11-26 [分享] RT7LITE精简后无法封装解决办法
2016-11-26 [讨论] 全新首发WIN7 32&64 WINSXS进一步精简批处理公测
2016-11-26 [原创] WINDOWS 7 精简教程之驱动精简 可用于64和32
2016-11-26 Win7精简成功后的总结
2016-11-26 [原创] RT7 Lite win7旗舰版精简方案
2016-11-26 [讨论] win7封装时如何直接开通局域网共享
2016-11-26 [教程] 离线封装原版WIN7系统 100%纯净