shell脚本,将文件里包含某个字符串的多行,全部整行替换为另一个字符串

有时候我们在一个文件里grep到了包含某个字符串的多行,想要替换这个字符串,我们用sed命令就可以实现,

可是有时候我们找到匹配的字符串后,不只是将匹配的字符串替换掉,还要把包含这个字符串的整行替换掉

我们同样可以用sed来实现,下面的做个示例

测试文本,我们要把包含172.24.0.95的那一整行,替换为别的文本
[root@localhost test]# cat test.log 
172.26.0.89
172.24.0.90
172.24.0.91
172.24.0.92
172.24.0.93
172.24.0.94
replace before 172.24.0.95
replace before 172.24.0.95
replace before 172.24.0.95
replace before 172.24.0.95
replace before 172.24.0.95
replace before 172.24.0.95
replace before 172.24.0.95
replace before 172.24.0.95
replace before 172.24.0.95
172.26.0.142
172.24.0.143

方法一:找到匹配行数,循环替换行

测试脚本:

[root@localhost test]# cat test.sh 
#!/bin/sh

lines=$(grep -n -w 172.24.0.95 test.log | cut -d':' -f1)

for line in ${lines[@]}; do
    sed -i ''$line'c  \\tthis is replaced 955555' test.log
done

方法一执行结果:

[root@localhost test]# ./test.sh 
[root@localhost test]# cat test.log 
172.26.0.89
172.24.0.90
172.24.0.91
172.24.0.92
172.24.0.93
172.24.0.94
	this is replaced 955555
	this is replaced 955555
	this is replaced 955555
	this is replaced 955555
	this is replaced 955555
	this is replaced 955555
	this is replaced 955555
	this is replaced 955555
	this is replaced 955555
172.26.0.142
172.24.0.143

方法二:用*通配符找到对应行,整行替换(推荐,较简单)

sed -i "/172.24.0.95/s/.*/this is replaced 955555/" test.log 

方法二执行结果:

 

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值