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

一. 需求

⏹有如下文件,现要求


二. 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
相关推荐
小白的码BUG之路14 分钟前
linux -- ssh两台机器相连
运维·服务器·ssh
缓慢更新2 小时前
表单引擎的存储建模:宽表与文档库的取舍
运维·服务器·网络·数据库·低代码·oracle·适配器模式
续写烂尾2 小时前
贴片 SD NAND、eMMC、TF 卡规格怎么定?硬件工程师选型清单
运维·服务器·网络
不昀2 小时前
网口Link Up后仍然掉线,怎样区分物理链路和数据通路问题?
linux·以太网
迪康妍妍2 小时前
终端管控实操:封堵网盘与IM外发通道的落地思路
运维·网络·安全·架构·安全性测试
sxgzzn2 小时前
如何选择合适的开关柜在线监测工具?
运维·重构·无人机·开关柜局放在线监测·光伏运维管理系统
Lhan.zzZ3 小时前
Qt WebEngineView 在 Linux 上无法加载网页:从“看不见 HTML“到“禁用沙箱“
linux·c++·qt
zxcvb1533 小时前
运维经验分享:监控网页更新内容的几种思路
运维
Fcy6484 小时前
Linux下 多路转接select详解
linux·select·多路转接
云飞云共享云桌面4 小时前
设计师共享单台图形服务器,解决 SolidWorks大装配卡顿难题
运维·服务器·3d·自动化·电脑·制造