案例一:grep 使用正则表达式匹配
# grep -E '([1-9][0-9]{0,2}\.){3}[1-9][0-9]{0,2}' /etc/sysconfig/network-scripts/ifcfg-ens192
IPADDR=192.168.8.31
GATEWAY=192.168.8.55
或者:
# egrep '([1-9][0-9]{0,2}\.){3}[1-9][0-9]{0,2}' /etc/sysconfig/network-scripts/ifcfg-ens192
IPADDR=192.168.8.31
GATEWAY=192.168.8.55
案例二:grep 显示行号
2.1 grep 显示某些关键字所在行行号
# egrep -n '([1-9][0-9]{0,2}\.){3}[1-9][0-9]{0,2}' /etc/sysconfig/network-scripts/ifcfg-ens192
16:IPADDR=192.168.8.31
18:GATEWAY=192.168.8.55
2.2 grep 显示哪些行号是空行
# egrep -n ^$ /etc/resolv.conf
案例三:grep 取反匹配
3.1 grep 取反不匹配某些关键字
# egrep -v '([1-9][0-9]{0,2}\.){3}[1-9][0-9]{0,2}' /etc/sysconfig/network-scripts/ifcfg-ens192
TYPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
BOOTPROTO=static
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=stable-privacy
NAME=ens192
UUID=5cda4d03-45c9-4856-80a6-f0bd0962d871
DEVICE=ens192
ONBOOT=yes
NETMASK=255.255.255.0
ZONE=public
3.2 grep 取反不显示空行
# egrep -v ^$ /etc/resolve.conf
### /etc/resolv.conf is a symlink to /var/run/netconfig/resolv.conf
### autogenerated by netconfig!
#
# Before you change this file manually, consider to define the
# static DNS configuration using the following variables in the
# /etc/sysconfig/network/config file:
# NETCONFIG_DNS_STATIC_SEARCHLIST
# NETCONFIG_DNS_STATIC_SERVERS
# NETCONFIG_DNS_FORWARDER
# or disable DNS configuration updates via netconfig by setting:
# NETCONFIG_DNS_POLICY=''
#
# See also the netconfig(8) manual page and other documentation.
#
### Call "netconfig update -f" to force adjusting of /etc/resolv.conf.
nameserver 192.168.0.1
案例四:grep 完全匹配
# egrep -o '([1-9][0-9]{0,2}\.){3}[1-9][0-9]{0,2}' /etc/sysconfig/network-scripts/ifcfg-ens192
192.168.8.31
192.168.8.55
案例五:grep 匹配区分大小写
# egrep -i '([1-9][0-9]{0,2}\.){3}[1-9][0-9]{0,2}' /etc/sysconfig/network-scripts/ifcfg-ens192
IPADDR=192.168.8.31
GATEWAY=192.168.8.55
案例六:grep 统计匹配成功次数
# egrep -c '([1-9][0-9]{0,2}\.){3}[1-9][0-9]{0,2}' /etc/sysconfig/network-scripts/ifcfg-ens192
2
案例七:grep 将匹配成功的部分自动添加颜色
# egrep --color=auto '([1-9][0-9]{0,2}\.){3}[1-9][0-9]{0,2}' /etc/sysconfig/network-scripts/ifcfg-ens192
IPADDR=192.168.8.31
GATEWAY=192.168.8.55
案例八:grep 将匹配成功的部分自动取消颜色
# egrep --color=no '([1-9][0-9]{0,2}\.){3}[1-9][0-9]{0,2}' /etc/sysconfig/network-scripts/ifcfg-ens192
IPADDR=192.168.8.31
GATEWAY=192.168.8.55
案例九:grep 一次匹配多个参数
# grep -e root -e zhumingyu /etc/passwd
root:x:0:0:root:/root:/bin/bash
zhumingyu:x:1001:1001:root:/root:/bin/bash