文本处理——grep

grep: Global search REgular expression and Print out the line
作用:文本搜索工具,根据用户指定的“模式”对目标文本逐行进行匹配检查;打印匹配到的行
模式:由正则表达式字符及文本字符所编写的过滤条件
格式:

grep [OPTIONS] PATTERN [FILE...]

常见选项:

-color=auto 对匹配到的文本着色显示
-m    #  匹配#次后停止
-v 显示不被pattern匹配到的行,即取反
-i 忽略字符大小写
-n 显示匹配的行号
-c 统计匹配的行数
-o 仅显示匹配到的字符串
-q 静默模式,不输出任何信息
-A # after, 后#行
-B # before, 前#行
-C # context, 前后各#行
-e 实现多个选项间的逻辑or关系,如:grep –e  'cat' -e 'dog'
-w 匹配整个单词
-E 使用ERE,相当于egrep
-F 不支持正则表达式,相当于fgrep
-f file 根据模式文件处理
-r 递归目录,但不处理软链接
-R 递归目录,但处理软链接

范例:取两个文件的相同行

[root@centos7 ~]# cat f1.txt 
a
b
c
1
2
3
[root@centos7 ~]# cat f2.txt 
1
2
3

[root@centos7 ~]# grep -of f1.txt f2.txt 	
1
2
3

范例:取分区利用率最大值

[root@centos7 ~]# df | grep '^/dev/sd' | tr -s ' ' % | cut -d% -f5 | sort -n | tail -1
[root@centos7 ~]# df | grep '^/dev/sd' | grep -oE '\<[0-9]{,3}%' | tr -d '%' | sort -nr | head -1
[root@centos7 ~]# df | grep '^/dev/sd' | grep -oE '\<[0-9]{,3}%' | grep -Eo '[0-9]+' | sort -nr | head -1

范例:取和当前主机建立连接数最多的前三位IP

[root@centos7 ~]# ss -nt | grep "^ESTAB" | tr -s ' ' : | cut -d: -f6 |sort | uniq -c |sort -nr | head -n3

范例:统计当前主机的连接状态

[root@centos7 ~]# ss -nta | grep -v '^State' | cut -d' ' -f1 | sort | uniq -c
[root@centos7 ~]# ss -ntl | tail -n +2 | cut -d ' ' -f1 | sort | uniq -c

范例:算出所有人的年龄总和

[root@centos7 ~]# cat /data/age.txt 
xiaoming=20
xiaohong=18
xiaoqiang=22

[root@centos7 ~]# cut -d= -f2 /data/age.txt | tr '\n' + | grep -Eo '.*[0-9]' | bc
[root@centos7 ~]# grep -Eo '[0-9]+' /data/age.txt | tr '\n' + | grep -Eo '.*[0-9]' | bc
[root@centos7 ~]# grep -Eo '[0-9]+' /data/age.txt | paste -s -d+ | bc
posted @   浅笑人伤  阅读(56)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示