天天看點

一文精通linux grep指令

01

簡介

在平時開發過程中,難免會檢視生産日志去追蹤問題原因。在海量日志中去查到我們想要的日志就無法避免使用grep指令。

grep (global search regular expression(RE) and print out the line,全面搜尋正規表達式并把行列印出來)是一種強大的文本搜尋工具,它能使用正規表達式搜尋文本,并把比對的行列印出來。

Unix的grep家族包括grep、egrep和fgrep。egrep和fgrep的指令隻跟grep有很小不同。egrep是grep的擴充,支援更多的re元字元, fgrep就是fixed grep或fast grep,它們把所有的字母都看作單詞,也就是說,正規表達式中的元字元表示回其自身的字面意義,不再特殊。linux使用GNU版本的grep。它功能更強,可以通過-G、-E、-F指令行選項來使用egrep和fgrep的功能。

02

grep常用用法

[root@www ~]# grep [-acinv] [--color=auto] '搜尋字元串' filename      

選項與參數:

-a :将 binary 檔案以 text 檔案的方式搜尋資料

-c :計算找到 '搜尋字元串' 的次數

-i :忽略大小寫的不同,是以大小寫視為相同

-n :順便輸出行号

-v :反向選擇,亦即顯示出沒有 '搜尋字元串' 内容的那一行!

--color=auto :可以将找到的關鍵詞部分加上顔色的顯示喔!

舉例:将/etc/passwd,有出現 root 的行取出來

# grep root /etc/passwd

root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin      

# cat /etc/passwd | grep root 

root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin      

舉例:将/etc/passwd,有出現 root 的行取出來,同時顯示這些行在/etc/passwd的行号

# grep -n root /etc/passwd

1:root:x:0:0:root:/root:/bin/bash
30:operator:x:11:0:operator:/root:/sbin/nologin      

在關鍵字的顯示方面,grep 可以使用 --color=auto 來将關鍵字部分使用顔色顯示。 這可是個很不錯的功能啊!但是如果每次使用 grep 都得要自行加上 --color=auto 又顯的很麻煩~ 此時那個好用的 alias 就得來處理一下啦!你可以在 ~/.bashrc 内加上這行:​

​alias grep='grep --color=auto​

​​再以​

​source ~/.bashrc​

​來立即生效即可喔! 這樣每次運作 grep 他都會自動幫你加上顔色顯示啦

舉例:将/etc/passwd,将沒有出現 root 的行取出來

# grep -v root /etc/passwd      

舉例:将/etc/passwd,将沒有出現 root 和nologin的行取出來

# grep -v root /etc/passwd | grep -v nologin      

舉例:用 dmesg 列出核心資訊,再以 grep 找出内含 eth 那行,要将捉到的關鍵字顯色,且加上行号來表示:

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

247:eth0: RealTek RTL8139 at 0xee846000, 00:90:cc:a6:34:84, IRQ 10248:eth0: Identified 8139 chip type 'RTL-8139C'
294:eth0: link up, 100Mbps, full-duplex, lpa 0xC5E1305:eth0: no IPv6 routers present      

用 dmesg 列出核心資訊,再以 grep 找出内含 eth 那行,在關鍵字所在行的前兩行與後三行也一起捉出來顯示

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

245-PCI: setting IRQ 10 as level-triggered
246-ACPI: PCI Interrupt 0000:00:0e.0[A] -> Link [LNKB] ...

247:eth0: RealTek RTL8139 at 0xee846000, 00:90:cc:a6:34:84, IRQ 10
248:eth0: Identified 8139 chip type 'RTL-8139C'

249-input: PC Speaker as /class/input/input2
250-ACPI: PCI Interrupt 0000:00:01.4[B] -> Link [LNKB] ...
251-hdb: ATAPI 48X DVD-ROM DVD-R-RAM CD-R/RW drive, 2048kB Cache, UDMA(66)      

如上所示,你會發現關鍵字 247 所在的前兩行及 248 後三行也都被顯示出來!

這樣可以讓你将關鍵字前後資料捉出來進行分析啦!

根據檔案内容遞歸查找目錄

# grep ‘energywise’ *           #在目前目錄搜尋帶'energywise'行的檔案

# grep -r ‘energywise’ *        #在目前目錄及其子目錄下搜尋'energywise'行的檔案

# grep -l -r ‘energywise’ *     #在目前目錄及其子目錄下搜尋'energywise'行的檔案,但是不顯示比對的行,隻顯示比對的檔案      

這幾個指令很使用,是查找檔案的利器。

03

grep與正規表達式

字元類

字元類的搜尋:如果我想要搜尋 test 或 taste 這兩個單字時,可以發現到,其實她們有共通的 't?st' 存在~這個時候,我可以這樣來搜尋:

[root@www ~]# grep -n 't[ae]st' regular_express.txt

8:I can't finish the test.
9:Oh! The soup taste good.      

其實 [] 裡面不論有幾個位元組,他都謹代表某一個位元組, 是以,上面的例子說明了,我需要的字串是『tast』或『test』兩個字串而已!

字元類的反向選擇 [^] :如果想要搜尋到有 oo 的行,但不想要 oo 前面有 g,如下

[root@www ~]# grep -n '[^g]oo' regular_express.txt

2:apple is my favorite food.
3:Football game is not use feet only.
18:google is the best tools for search keyword.
19:goooooogle yes!      

第 2,3 行沒有疑問,因為 foo 與 Foo 均可被接受!

但是第 18 行明明有 google 的 goo 啊~别忘記了,因為該行後面出現了 tool 的 too 啊!是以該行也被列出來~ 也就是說, 18 行裡面雖然出現了我們所不要的項目 (goo) 但是由於有需要的項目 (too) , 是以,是符合字串搜尋的喔!

至於第 19 行,同樣的,因為 goooooogle 裡面的 oo 前面可能是 o ,例如: go(ooo)oogle ,是以,這一行也是符合需求的!

字元類的連續:再來,假設我 oo 前面不想要有小寫位元組,是以,我可以這樣寫 [^abcd....z]oo , 但是這樣似乎不怎麼友善,由於小寫位元組的 ASCII 上編碼的順序是連續的, 是以,我們可以将之簡化為底下這樣:

[root@www ~]# grep -n '[^a-z]oo' regular_express.txt

3:Football game is not use feet only.      

也就是說,當我們在一組集合位元組中,如果該位元組組是連續的,例如大寫英文/小寫英文/數字等等, 就可以使用[a-z],[A-Z],[0-9]等方式來書寫,那麼如果我們的要求字串是數字與英文呢? 呵呵!就将他全部寫在一起,變成:[a-zA-Z0-9]。

我們要取得有數字的那一行,就這樣:

[root@www ~]# grep -n '[0-9]' regular_express.txt

5:However, this dress is about $ 3183 dollars.
15:You are the best is mean you are the no. 1.      

行首與行尾位元組 ^ $

行首字元:如果我想要讓 the 隻在行首列出呢? 這個時候就得要使用定位位元組了!我們可以這樣做:

[root@www ~]# grep -n '^the' regular_express.txt

12:the symbol '*' is represented as start.      

此時,就隻剩下第 12 行,因為隻有第 12 行的行首是 the 開頭啊~此外, 如果我想要開頭是小寫位元組的那一行就列出呢?可以這樣:

[root@www ~]# grep -n '^[a-z]' regular_express.txt

2:apple is my favorite food.
4:this dress doesn't fit me.
10:motorcycle is cheap than car.
12:the symbol '*' is represented as start.
18:google is the best tools for search keyword.
19:goooooogle yes!
20:go! go! Let's go.      

如果我不想要開頭是英文字母,則可以是這樣:

[root@www ~]# grep -n '^[^a-zA-Z]' regular_express.txt

1:"Open Source" is a good mechanism to develop programs.
21:# I am VBird      

^ 符号,在字元類符号(括号[])之内與之外是不同的! 在 [] 内代表『反向選擇』,在 [] 之外則代表定位在行首的意義!

那如果我想要找出來,行尾結束為小數點 (.) 的那一行:

[root@www ~]# grep -n '\.$' regular_express.txt

1:"Open Source" is a good mechanism to develop programs.
2:apple is my favorite food.
3:Football game is not use feet only.
4:this dress doesn't fit me.10:motorcycle is cheap than car.11:This window is clear.
12:the symbol '*' is represented as start.
15:You are the best is mean you are the no. 1.
16:The world <Happy> is the same with "glad".
17:I like dog.
18:google is the best tools for search keyword.
20:go! go! Let's go.      

特别注意到,因為小數點具有其他意義(底下會介紹),是以必須要使用轉義字元()來加以解除其特殊意義!

找出空白行:

[root@www ~]# grep -n '^$' regular_express.txt

22:      

因為隻有行首跟行尾 (^$),是以,這樣就可以找出空白行啦!

任意一個位元組 . 與重複位元組 *

這兩個符号在正規表達式的意義如下:

. (小數點):代表『一定有一個任意位元組』的意思;* (星号):代表『重複前一個字元, 0 到無窮多次』的意思,為組合形态

假設我需要找出 g??d 的字串,亦即共有四個位元組, 起頭是 g 而結束是 d ,我可以這樣做:

[root@www ~]# grep -n 'g..d' regular_express.txt

1:"Open Source" is a good mechanism to develop programs.
9:Oh! The soup taste good.
16:The world <Happy> is the same with "glad".      

因為強調 g 與 d 之間一定要存在兩個位元組,是以,第 13 行的 god 與第 14 行的 gd 就不會被列出來啦!

如果我想要列出有 oo, ooo, oooo 等等的資料, 也就是說,至少要有兩個(含) o 以上,該如何是好?

因為 * 代表的是『重複 0 個或多個前面的 RE 字元』的意義, 是以,『o』代表的是:『擁有空位元組或一個 o 以上的位元組』,是以,『 grep -n 'o' regular_express.txt 』将會把所有的資料都列印出來終端上!

當我們需要『至少兩個 o 以上的字串』時,就需要 ooo* ,亦即是:

[root@www ~]# grep -n 'ooo*' regular_express.txt

1:"Open Source" is a good mechanism to develop programs.
2:apple is my favorite food.
3:Football game is not use feet only.
9:Oh! The soup taste good.
18:google is the best tools for search keyword.
19:goooooogle yes!      

如果我想要字串開頭與結尾都是 g,但是兩個 g 之間僅能存在至少一個 o ,亦即是 gog, goog, gooog.... 等等,那該如何?

[root@www ~]# grep -n 'goo*g' regular_express.txt

18:google is the best tools for search keyword.
19:goooooogle yes!      

如果我想要找出 g 開頭與 g 結尾的行,當中的字元可有可無

[root@www ~]# grep -n 'g.*g' regular_express.txt

1:"Open Source" is a good mechanism to develop programs.
14:The gd software is a library for drafting programs.
18:google is the best tools for search keyword.
19:goooooogle yes!
20:go! go! Let's go.      

因為是代表 g 開頭與 g 結尾,中間任意位元組均可接受,是以,第 1, 14, 20 行是可接受的喔! 這個 .* 的 RE 表示任意字元是很常見的.

如果我想要找出『任意數字』的行?因為僅有數字,是以就成為:

[root@www ~]# grep -n '[0-9][0-9]*' regular_express.txt

5:However, this dress is about $ 3183 dollars.
15:You are the best is mean you are the no. 1.      

限定連續 RE 字元範圍 {}

我們可以利用 . 與 RE 字元及 * 來配置 0 個到無限多個重複位元組, 那如果我想要限制一個範圍區間内的重複位元組數呢?

舉例來說,我想要找出兩個到五個 o 的連續字串,該如何作?這時候就得要使用到限定範圍的字元 {} 了。 但因為 { 與 } 的符号在 shell 是有特殊意義的,是以, 我們必須要使用字元 \ 來讓他失去特殊意義才行。 至於 {} 的文法是這樣的,假設我要找到兩個 o 的字串,可以是:

[root@www ~]# grep -n 'o\{2\}' regular_express.txt

1:"Open Source" is a good mechanism to develop programs.
2:apple is my favorite food.
3:Football game is not use feet only.
9:Oh! The soup taste good.
18:google is the best tools for search ke
19:goooooogle yes!      

假設我們要找出 g 後面接 2 到 5 個 o ,然後再接一個 g 的字串,他會是這樣:

[root@www ~]# grep -n 'go\{2,5\}g' regular_express.txt

18:google is the best tools for search keyword.      

如果我想要的是 2 個 o 以上的 goooo....g 呢?除了可以是 gooo*g ,也可以是:

[root@www ~]# grep -n 'go\{2,\}g' regular_express.txt

18:google is the best tools for search keyword.
19:goooooogle yes!      

擴充grep(grep -E 或者 egrep):

使用擴充grep的主要好處是增加了額外的正規表達式元字元集。

列印所有包含NW或EA的行。如果不是使用egrep,而是grep,将不會有結果查出。

# egrep 'NW|EA' testfile    

northwest       NW      Charles Main        3.0     .98     3       34
eastern         EA      TB Savage           4.4     .84     5       20      

對于标準grep,如果在擴充元字元前面加\,grep會自動啟用擴充選項-E。

#grep 'NW\|EA' testfile

northwest       NW      Charles Main        3.0     .98     3       34
eastern         EA      TB Savage           4.4     .84     5       20      

搜尋所有包含一個或多個3的行。

# egrep '3+' testfile
# grep -E '3+' testfile
# grep '3\+' testfile              

這3條指令的結果将會

northwest       NW      Charles Main          3.0     .98     3       34
western         WE      Sharon Gray           5.3     .97     5       23
northeast       NE      AM Main Jr.           5.1     .94     3       13
central         CT      Ann Stephens          5.7     .94     5       13      

搜尋所有包含0個或1個小數點字元的行。

# egrep '2\.?[0-9]' testfile
# grep -E '2\.?[0-9]' testfile
# grep '2\.\?[0-9]' testfile      

首先含有2字元,其後緊跟着0個或1個點,後面再是0和9之間的數字。

western         WE       Sharon Gray          5.3     .97     5       23
southwest       SW      Lewis Dalsass         2.7     .8      2       18
eastern         EA       TB Savage             4.4     .84     5       20      

搜尋一個或者多個連續的no的行。

# egrep '(no)+' testfile
# grep -E '(no)+' testfile
# grep '\(no\)\+' testfile         

3個指令傳回相同結果,

northwest       NW      Charles Main        3.0     .98     3       34
northeast       NE       AM Main Jr.        5.1     .94     3       13
north           NO      Margot Weber        4.5     .89     5       9      

不使用正規表達式

fgrep  '*' /etc/profile
for i in /etc/profile.d/*.sh ; do      
grep -F '*' /etc/profile
for i in /etc/profile.d/*.sh ; do