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

shell脚本,将文件里包含某个字符串的多行,全部整行替换为另一个字符串有时候我们在一个文件里 grep 到了包含某个字符串的多行 想要替换这个字符串 我们用 sed 命令就可以实现 可是有时候我们找到匹配的字符串后 不只是将匹配的字符串替换掉 还要把包含这个字符串的整行替换掉 我们同样可以用 sed 来实现 下面的做个示例 测试文本 我们要把包含 172 24

大家好,我是讯享网,很高兴认识大家。

有时候我们在一个文件里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 ' 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  this is replaced  this is replaced  this is replaced  this is replaced  this is replaced  this is replaced  this is replaced  this is replaced  172.26.0.142 172.24.0.143 

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

讯享网sed -i "/172.24.0.95/s/.*/this is replaced /" test.log 

方法二执行结果:

 

小讯
上一篇 2025-03-05 10:49
下一篇 2025-01-11 08:36

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/94763.html