利用grep與正則表達式快速精確實現文本通配

什麼是grep?

    grep (global search regular expression(RE) and print out the line,其全稱意義爲全局搜索正則表達式,並打印出來。是一種功能強大,簡單易用的文本搜索工具。它能根據其後指定的匹配方式匹配出文件中的文本,並把匹配到的那整行都打印出來。

    在Linux中grep家族有三個成員,分別是grep,egrep和fgrep,其使用方法略有不同,其中egrep是grep的擴展,而fgrep則是在進行文本通配時把所有的字母都當做單詞來處理,讓正則表達式中的元字符失去意義,當成普通單詞來處理。在使用的時候可以用grep後接-E或者-F選項實現egrep和fgrep的功能。

grep的常用選項和一般用法。

    grep的常常用選項有以下幾個

    -v:反向顯示查找文本,即匹配到的反而不顯示,顯示未被匹配到的字符。

        例:正常匹配文件test中的“hello“字符串         

            [root@grep tmp]# grep "hello" test

            hello

            加-v選項

            [root@grep tmp]# grep -v "hello" test

            this is a test txt

            welcome to use grep

    -i:文本匹配中忽略大小寫   

            [root@grep tmp]# grep -i "HOW ARE YOU" test

            HOW ARE YOU

            how are you        

    -n:在輸出文本時顯示其行號

            [root@grep tmp]# grep -n "how are you" test

            5:how are you

    -c:顯示被匹配到的次數     

            [root@grep tmp]# grep -ic "how are you" test

            2

    --color=auto:用此選項顯示被匹配到的字符串 

            [root@grep tmp]# grep --color=auto "how" test

            how are you

其他選項不再贅述,可通過查看grep幫助文檔查看。

grep結合正則表達式實現快速準確匹配文本。

    結合grep與正則表達式,能快速準確地找到所希望匹配到的字符串和行,加快工作效率。

    例1:找出/etc/passwd文件中root所在的行

        [root@grep tmp]# grep --color=auto "^root" /etc/passwd

        root:x:0:0:root:/root:/bin/bash

    例2:找出/tec/passwd文件中的系統賬號,顯示其用戶名和UID        

        [root@grep tmp]# cut -d: -f1,3 /etc/passwd|grep --color=auto "\<[1-4[0-9][0-9]\>"

        uucp:10

        operator:11

        games:12

        gopher:13

        ftp:14

        nobody:99

        dbus:81

        vcsa:69

        haldaemon:68

        gdm:42

        ntp:38

        apache:48

        postfix:89

        sshd:74

        tcpdump:72

        named:25

    例3:取字符串/etc/sysconfig/的基名

        [root@grep tmp]#  echo /etc/sysconfig |grep -E -o "/[[:alpha:]]*$" | grep -o -E "[[:alnum:]]*"

        sysconfig

    例4:匹配出testip文件中合理的ip地址        

        root@grep tmp]# cat testip

        192168.0.1

        192.155.234.2

        256.234.245.654

        123.234.212.12

        1.0.0.1  

        [root@grep tmp]# cat testip |grep  --colorauto -E "(^\b[1-9]\b|^\b[1-9][0-9]\b|^\b1[0-9][0-9]\b|^\b2[1-3[0-9])\.(\b[0-9]\b|\b[1-9][0-9]\b|\b1[0-9][0-9]\b|\b2[0-4][0-9]\b|\b25[0-5]\b)\.(\b[0-9]\b|\b[1-9][0-9]\b|\b1[0-9][0-9]\b|\b2[0-4][0-9]\b|\b25[0-5]\b)\.(\b[0-9]\b|\b[1-9][0-9]\b|\b1[0-9][0-9]\b|\b2[0-4][0-9]\b|\b25[0-5]\b)$"

        192.155.234.2

        123.234.212.12

        1.0.0.1

         

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章