1. 程式人生 > >Linux grep命令使用大全

Linux grep命令使用大全

grep是一種使用正則表示式的多用途文字搜尋工具(global search regular expression(RE) and print out the line)
主要引數:
-c:僅僅輸出匹配行的計數。
-I:不區分大 小寫(僅僅適用於單字元)。
-h:查詢多檔案時不顯示檔名稱。
-l:查詢多檔案時僅僅輸出包括匹配字元的檔名稱。
-n:顯示匹配行及 行號。
-s:不顯示不存在或無匹配文字的錯誤資訊。
-v:顯示不包括匹配文字的全部行。
grep 'test' testfile.txt # 從檔案中查詢匹配'test'的的內容,如可為'testaa','atest'乖乖
ls | grep
-i 'test' #忽略大小寫進行匹配 grep -w 'test' testfile.txt # 匹配整個單詞,如'testaa'不列出 grep -n 'test' testfile.txt # 顯示行號進行匹配 grep -v 'test' testfile.txt # 將沒有出現'test'的行取出來 grep -A3 'testa' testfile.txt # 在匹配行列印完畢後再列印3行 grep -B5 'testa' testfile.txt # 在匹配行前列印5行 grep -C8 'testa' testfile.txt # 在前後各自列印8行 grep 'test'
* # 在當前目錄搜尋帶'test'行的檔案 grep -r 'test' * # 在當前目錄及其子目錄下搜尋'test'行的檔案 grep -l -r 'test' * # 在當前目錄及其子目錄下搜尋'test'行的檔案,但是不顯示匹配的行,只顯示匹配的檔案 grep -c "*baidu.com*" test.txt # 統計匹配行數
grep --color "test" test.txt # 加上著色
30 black
31 red
32 green
33 yellow
34 blue
35 purple
36 cyan
37 white

自定義顏色:
GREP_COLOR=32
 # 以下是 grep 與正則表示式的結合
 grep -n 't[ae]st' test.txt
 grep -n '[^g]oo' test.txt # 搜尋到有 oo 的行,但不想要 oo 前面有 g,並顯示行號
 grep -n '[^a-z]oo' test.txt # 搜尋到有 oo 的行,但不想要 oo 前面有小寫字母
 grep -n '[0-9]' test.txt # 取得有數字的行
 grep -n '^the' test.txt # 搜尋出以'the'開頭的行
 grep -n '^[a-z]' test.txt # 搜尋出以小寫字母開頭的行
 grep -n '^[^a-zA-Z]' test.txt # 搜尋出不是字母開頭的行
 grep -n '\.$' test.txt # 行尾結束為小數點 (.) 的行
 grep -n '^$' test.txt # 找出空白行
 grep -n 'g..d' test.tx # 找出包含'g??d'字序列
 grep -n 'ooo*' test.txt
 grep -n 'goo*g' test.txt

 grep -n 'o\{2\}' test.txt # 搜尋出含有2個'o'的行
 grep -n 'go\{2,5\}g' test.txt # 找出 g 後面接 2 到 5 個 o ,然後再接一個 g 的字串

另外參考:egrep

ls | grep -E "file1|file2" # -E 選項可使用多個檔案
ls | egrep "file1|file2"