天天看點

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           

收工,拜了個拜。。。