天天看点

Linux-文本处理三剑客之grep

作者:不寐旋律
  • grep 命令主要对文本的(正则表达式)行基于模式进行过滤
  • sed:stream editor,文本编辑工具
  • awk:Linux上的实现gawk,文本报告生成器

1 文本处理三剑客之 grep

grep: Global search REgular expression and Print out the line

作用:文本搜索工具,根据用户指定的“模式”对目标文本逐行进行匹配检查;打印匹配到的行

模式:由正则表达式字符及文本字符所编写的过滤条件

格式:

grep [选项]... 模式 文件...

常见选项:

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

案例:

[root@nginx ~]# grep root /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
[root@nginx ~]#           

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

[root@nginx ~]#cat f1.txt
a
b
1
c
[root@nginx ~]#cat f2.txt
b
e
f
c
1
2
[root@nginx ~]#grep -f f1.txt  f2.txt
b
c
1
 
            

案例: 分区利用率最大的值

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

案例:统计连接状态数

[root@nginx ~]# ss -nta | grep -v '^State' |cut -d" " -f1|sort |uniq -c
      1 ESTAB
      4 LISTEN
[root@nginx ~]#
[root@nginx ~]#  ss -nta | tail -n +2 |cut -d" " -f1|sort |uniq -c
      1 ESTAB
      4 LISTEN
[root@nginx ~]#           

案例:排除掉空行和#开头的行

[root@nginx ~]#grep -v "^#" /etc/profile | grep -v '^#39;
[root@nginx ~]#grep -v "^#\|^#34; /etc/profile
[root@nginx ~]#grep -v "^\(#\|$\)" /etc/profile 
[root@nginx ~]#grep -Ev "^(#|$)" /etc/profile
[root@nginx ~]#egrep -v "^(#|$)" /etc/profile
 
            

案例:过滤网卡信息

[root@nginx ~]# ifconfig | grep -E '[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}'
        inet 192.168.223.111  netmask 255.255.255.0  broadcast 192.168.223.255
        inet 127.0.0.1  netmask 255.0.0.0
[root@nginx ~]# 

[root@nginx ~]# ifconfig | grep -Eo '([0-9]{1,3}\.){3}[0-9]{1,3}'|head -1
192.168.223.111
[root@nginx ~]#            

案例:过滤关键词为root和bash的行

[root@nginx ~]# grep -E 'root|bash' /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
lisi:x:1002:1002::/home/lisi:/bin/bash
zhangsan:x:1003:1003::/home/zhangsan:/bin/bash

[root@nginx ~]# grep -e 'root' -e 'bash' /etc/passwd

[root@nginx ~]# grep -w root /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
[root@nginx ~]#            

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

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

[root@nginx ~]#cut -d"=" -f2 /data/age.txt|tr '\n' + | grep -Eo ".*[0-9]"|bc
60
[root@nginx ~]#grep -Eo "[0-9]+" /data/age.txt | tr '\n' + | grep -Eo ".*[0-9]"|bc
60
[root@nginx ~]#grep -oE '[0-9]+' /data/age.txt| paste -s -d+|bc
60           

收工,拜了个拜。。。