您的位置:首页 > 科技 > 能源 > Linux grep技巧 删除含有指定关键词的行,创建新文件

Linux grep技巧 删除含有指定关键词的行,创建新文件

2024/10/5 14:13:26 来源:https://blog.csdn.net/feyehong/article/details/139967599  浏览:    关键词:Linux grep技巧 删除含有指定关键词的行,创建新文件

一. 需求

⏹有如下文件,现要求

  • 删除含有xuecheng关键字的行
  • 删除含有192.168.1.1关键字的行
  • 也就是说,最终只会留下127.0.0.1 license.sublimehq.com
127.0.0.1 www.xuecheng.com
127.0.0.1 img.xuecheng.com
192.168.1.1 www.test.com
127.0.0.1 video.xuecheng.com
127.0.0.1 teacher.xuecheng.com
127.0.0.1 system.xuecheng.com
127.0.0.1 ucenter.xuecheng.com
127.0.0.1 license.sublimehq.com

二. grep -v 排除

⏹方式1

  • -E:用来指定正则表达式
  • -v:用来排除
grep -E "xuecheng|192.168.1.1" -v ./hosts
# 查看hosts文件内容
fengyehong@ubuntu:~/jmw_work_space/20240625$ cat hosts
127.0.0.1 www.xuecheng.com
127.0.0.1 img.xuecheng.com
192.168.1.1 www.test.com
127.0.0.1 video.xuecheng.com
127.0.0.1 teacher.xuecheng.com
127.0.0.1 system.xuecheng.com
127.0.0.1 ucenter.xuecheng.com
127.0.0.1 license.sublimehq.com# 排除指定的行
fengyehong@ubuntu:~/jmw_work_space/20240625$ grep -E "xuecheng|192.168.1.1" -v ./hosts
127.0.0.1 license.sublimehq.com

⏹方式2

grep -v "xuecheng" ./hosts | grep -v "192.168.1.1"
# 查看hosts文件内容
fengyehong@ubuntu:~/jmw_work_space/20240625$ cat hosts
127.0.0.1 www.xuecheng.com
127.0.0.1 img.xuecheng.com
192.168.1.1 www.test.com
127.0.0.1 video.xuecheng.com
127.0.0.1 teacher.xuecheng.com
127.0.0.1 system.xuecheng.com
127.0.0.1 ucenter.xuecheng.com
127.0.0.1 license.sublimehq.com# 先使用-v排除掉xuecheng关键字之后,再使用-v排除192.168.1.1关键字
fengyehong@ubuntu:~/jmw_work_space/20240625$ grep -v "xuecheng" ./hosts | grep -v "192.168.1.1"
127.0.0.1 license.sublimehq.com

三. 创建新文件

grep -v "xuecheng" ./hosts | grep -v "192.168.1.1" > new_hosts

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com