linux shell搜索某个字符串,然后在后面加上字符串?字符串后面插入字符串?sed字符串后面插入字符串?

需求描述:

  今天在配置nrpe.cfg这个文件,里面有allowed_hosts的IP地址,需要加上监控主机的地址,所以首先要搜索

  到这个地址,然后呢,加上监控主机的地址,考虑通过sed命令来实现

操作过程

1.查看原文件

[root@testvm02 ~]# cat nrpe.cfg 
allowed_hosts=127.0.0.1

2.通过sed命令,在后面加上监控端的主机IP

复制代码
[root@testvm02 ~]# sed -i 's/allowed_hosts=127.0.0.1/&,192.168.53.25/' nrpe.cfg #通过-i表示直接对文件进行操作s表示替换通过&+字符串,来实现将新的字符串增加到找到得字符串的后面.
[root@testvm02 ~]# cat nrpe.cfg   #重新查看文件的内容,已经在原来的字符串后面加上了新的字符串(带有逗号的字符串)
allowed_hosts=127.0.0.1,192.168.53.25



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

0000AAA11112222

 

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

0000AAA1111BBB2222

 

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

0000BBB1111AAA2222

test

 要求:在每行的头添加字符,比如"HEAD",命令如下:

1

2

3

4

5

6

[root@localhost ~]# sed -i 's/^/HEAD&/' /tmp/input.txt 

[root@localhost ~]# cat /tmp/input.txt

HEADnull

HEAD000011112222

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

HEAD000011112222tail

HEADtail

HEADtesttail

说明:
1."^"代表行首,"$"代表行尾
2.'s/$/&tail/g'中的字符g代表每行出现的字符全部替换,如果想在特定字符处添加,g就有用了,否则只会替换每行第一个,而不继续往后找。

复制代码
posted @   技术颜良  阅读(3027)  评论(0编辑  收藏  举报
编辑推荐:
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
阅读排行:
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 上周热点回顾(2.17-2.23)
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
历史上的今天:
2019-01-10 kubeadm安装Kubernetes V1.10集群详细文档
点击右上角即可分享
微信分享提示