Shell三剑客之grep

前言:

Shell三剑客是grep、sed和awk三个工具的简称,因功能强大,使用方便且使用频率高,因此被戏称为三剑客,熟练使用这三个工具可以极大地提升运维效率。

grep是文本查找或搜索工具,用于查找内容包含指定的范本样式的文本。它会一行一行循环匹配,匹配到相应的值时会先输出,然后换行继续匹配再换行直到所有的内容都匹配完。

1. 常用参数

bash 复制代码
-n:显示行号;
-i:忽略大小写;
-o:精准匹配;
-f:从文件每一行获取匹配模式;
-c:统计匹配的行数;
-w:匹配 整个单词;
-E:使用扩展正则表达式,相当于egrep;
-F :相当于fgrep,就是将pattern视为固定字符串。
-v:反转查找,显示不被 pattern 匹配到的行,相当于[^] 反向匹配;
-A:后面可加数字,为 after 的意思,除了列出该行外,后续的 n 行也列出来;
-B:后面可加数字,为 before 的意思,除了列出该行外,前面的 n 行也列出来;
-C:后面可加数字,为context 的意思,除了列出该行外,前后的n行也列出来。

2. 示例

**1)**查找多个文件中相同的内容

bash 复制代码
[root@test02 ~]# grep "NUMBER" file1.txt file2.txt
file1.txt:NUMBER=100
file2.txt:NUMBER=10

**2)**过滤以#开头的行和空白行

bash 复制代码
[root@test02 ~]# egrep -v "^#|^$"  a.txt 
fsjdf
fdfs

**3)**计算匹配项的数目

bash 复制代码
[root@test02 ~]# cat /etc/passwd| grep -c nologin
16

**4)**输出正则匹配到的内容

bash 复制代码
[root@test02 ~]# echo 'this is a test shell!' |grep -oE "[a-z]+"
this
is
a
test
shel

**5)**只显示匹配的字符串

bash 复制代码
[root@test02 ~]#  echo 'this is a test' |grep -o 'is'
is
is

**6)**匹配显示所有IP

bash 复制代码
[root@test02 ~]# ifconfig |grep -E -o "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
192.168.10.12
255.255.255.0
192.168.10.255
127.0.0.1
255.0.0.0

7**)删除K8S节点所有包含google的镜像**

bash 复制代码
root@node01:~# crictl rmi `crictl image | grep google | awk '{print $3}'` 
Deleted: registry.aliyuncs.com/google_containers/csi-external-health-monitor-controller:v0.10.0
Deleted: registry.aliyuncs.com/google_containers/snapshot-controller:v6.3.1
Deleted: registry.aliyuncs.com/google_containers/kube-webhook-certgen:v20230407
Deleted: registry.aliyuncs.com/google_containers/csi-provisioner:v3.6.0
Deleted: registry.cn-hangzhou.aliyuncs.com/google_containers/metrics-server:v0.7.0
Deleted: registry.aliyuncs.com/google_containers/csi-resizer:v1.9.0
Deleted: registry.aliyuncs.com/google_containers/csi-snapshotter:v6.3.0
Deleted: registry.aliyuncs.com/google_containers/hostpathplugin:v1.9.0
Deleted: registry.aliyuncs.com/google_containers/kube-proxy:v1.29.0
Deleted: registry.aliyuncs.com/google_containers/livenessprobe:v2.11.0
Deleted: registry.aliyuncs.com/google_containers/coredns:v1.11.1
Deleted: registry.aliyuncs.com/google_containers/csi-attacher:v4.4.0
Deleted: registry.aliyuncs.com/google_containers/csi-node-driver-registrar:v2.9.0
Deleted: registry.aliyuncs.com/google_containers/nginx-ingress-controller:v1.8.2
相关推荐
模型时代3 分钟前
Linux系统安全革命:Amutable公司推出全新验证完整性技术
linux·运维·系统安全
醇氧6 分钟前
【Linux】centos 防火墙学习
linux·学习·centos
~光~~9 分钟前
【嵌入式linux学习】06_中断子系统
linux·单片机·学习
LYS_061810 分钟前
寒假学习(14)(HAL库5)
java·linux·学习
神一样的老师11 分钟前
【ELF2学习开发板】Linux 命令行读取 MPU6050 传感器数据(I2C 总线)实战
linux·运维·学习
郝学胜-神的一滴13 分钟前
Linux网络编程中的connect函数:深入探索网络连接的基石
linux·服务器·网络·c++·websocket·程序人生
春日见14 分钟前
window wsl环境: autoware有日志,没有rviz界面/ autoware起不来
linux·人工智能·算法·机器学习·自动驾驶
翼龙云_cloud17 分钟前
亚马逊云代理商: RDS 误删实例急救指南 5 步找回数据
服务器·云计算·aws
翼龙云_cloud18 分钟前
阿里云代理商: 如何选择适合自己的阿里云 ECS 配置?
服务器·阿里云·云计算
jmxwzy18 分钟前
Linux常用命令
linux