shell grep正则表达式

关于grep一些简单小案例:

#查看系统内存、缓存、交换分区 -e的作用是匹配多个表达式

[root@shell ~]# cat /proc/meminfo|grep -e Mem -e Cache -e Swap

===================================================

查找/etc目录下的所有文件中的邮件地址;

[root@shell ~]# grep -R -o -n -E '[a-z0-9]+@[a-z0-9]+.[a-z]{2,4}' /etc

其中:-R:递归,-n表示匹配的行号,-o只输出匹配内容

-E:支持扩展正则表达式

===================================================

#查找/etc/目录下文件包含"HOSTNAME"的次数,-c统计匹配次数,-v取反

[root@shell ~]# grep -R -c 'HOSTNAME' /etc/|grep -v "0$"

===================================================

#查找内核日志中eth的行,显示颜色及行号:

[root@shell ~]# dmesg | grep -n --color=auto 'eth'

===================================================

#用dmesg列出核心信息,再以grep找出含有eth哪行,

在关键字所在行的前两行与后三行也一起找出出来显示

[root@shell ~]# dmesg |grep -n -A3 -B2 --color=auto 'eth'

===================================================

#统计系统中能登录的用户的个数

[root@shell ~]# cat /etc/passwd |grep -c bash$

===================================================

#统计httpd进程数量

[root@shell ~]# ps -ef|grep -c httpd

===================================================

#显示games 匹配的“-C”前后4行

[root@shell ~]# grep -C 4 'games' --color /etc/passwd

===================================================

#获取网卡名称:

[root@shell ~]# ip a |grep -E '^[0-9]' |awk -F:'{print $2}'

===================================================

#截取ip地址,[^]*表示以非空字符作为结束符,[0-9.]*表示

数字和点的结合。

[root@shell ~]# ifconfig eth0|grep -E -o 'inet addr:[^]*'

|grep -o'[0-9.]*'

===================================================

#截取MAC地址:

[root@shell ~]# ifconfig eth0|grep -i hwaddr |awk '{print$5}'

===================================================

#查看指定进程:

[root@shell ~]# ps -ef|grep mysql

root 1688 1645 0 05:02 pts/0  00:00:00 grep mysql

[root@shell ~]# ps -ef |grep svn

root 1684 1645 0 05:16  pts/0  00:00:00 grep svn

原文地址:https://www.cnblogs.com/kwzblog/p/12720287.html