一. 需求
⏹有如下文件,现要求
-
删除含有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
:用来排除
bash
grep -E "xuecheng|192.168.1.1" -v ./hosts
bash
# 查看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
bash
grep -v "xuecheng" ./hosts | grep -v "192.168.1.1"
bash
# 查看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
三. 创建新文件
bash
grep -v "xuecheng" ./hosts | grep -v "192.168.1.1" > new_hosts