linux中sed在指定字符前后添加内容
假设文档内容如下:
1 2 3 4 5 | [root@localhost ~]# cat /tmp/input.txt null 000011112222 test |
要求:在1111之前添加AAA,方法如下:
sed -i 's/指定的字符/要插入的字符&/' 文件
1 2 3 4 5 6 | [root@localhost ~]# sed -i 's/1111/AAA&/' /tmp/input.txt [root@localhost ~]# cat /tmp/input.txt null 0000 AAA 11112222 test |
要求:在1111之后添加BBB,方法如下:
sed -i 's/指定的字符/&要插入的字符/' 文件
1 2 3 4 5 6 | [root@localhost ~]# sed -i 's/1111/&BBB/' /tmp/input.txt [root@localhost ~]# cat /tmp/input.txt null 0000 AAA 1111 BBB 2222 test |
要求:(1) 删除所有空行;(2) 一行中,如果包含"1111",则在"1111"前面插入"AAA",在"11111"后面插入"BBB"
1 2 3 4 | [root@localhost ~]# sed '/^$/d;s/1111/AAA&/;s/1111/&BBB/' /tmp/input.txt null 0000 BBB 1111 AAA 2222 test |
要求:在每行的头添加字符,比如"HEAD",命令如下:
1 2 3 4 5 6 | [root@localhost ~]# sed -i 's/^/HEAD&/' /tmp/input.txt [root@localhost ~]# cat /tmp/input.txt HEADnull HEAD 000011112222 HEAD HEADtest |
要求:在每行的尾部添加字符,比如"tail",命令如下:
1 2 3 4 5 6 | [root@localhost ~]# sed -i 's/$/&tail/' /tmp/input.txt [root@localhost ~]# cat /tmp/input.txt HEADnulltail HEAD 000011112222 tail HEADtail HEADtesttail |
说明:
1."^"代表行首,"$"代表行尾
2.'s/$/&tail/g'中的字符g代表每行出现的字符全部替换,如果想在特定字符处添加,g就有用了,否则只会替换每行第一个,而不继续往后找。
如对您有帮助,支持下呗!
微信

支付宝

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?