描述:在文件中按行搜索關鍵字符串正則表達式
用法:grep [-acinv] [--color=auto] [-A n] [-B n] 'string' 文件名shell
-a:將二進制文檔以文本方式處理bash
-c:顯示匹配次數google
-i:忽略大小寫差別spa
-n:在行首顯示行號code
-v:顯示沒有匹配行遞歸
-r:遞歸搜索目錄或子目錄下匹配的字所在文件(可配合find命令 )ci
-A:After的意思,顯示匹配部分以後n行文檔
-B:before的意思,顯示匹配部分以前n行字符串
--color:以特定顏色高亮顯示匹配關鍵字
ps: .bashrc或者.bash_profile文件中加入:
alias grep=grep --color=auto
注意:
‘搜尋字符串’是正則表達式,注意爲了不shell的元字符對正則表達式的影響,請用單引
(’’)括起來,千萬不要用雙引號括起來("」)或者不括起來。
基本正則表達式:
元數據 |
意義和範例 |
^word | 搜尋以word開頭的行。
例如:搜尋以#開頭的腳本註釋行 grep –n ‘^#’ regular.txt
|
word$ | 搜尋以word結束的行
例如,搜尋以‘\.’結束的行 grep –n ‘\.$’ regular.txt
|
. | 匹配任意一個字符。
例如:grep –n ‘e.e’ regular.txt 匹配e和e之間有任意一個字符,能夠匹配eee,eae,eve,可是不匹配ee。
|
\ | 轉義字符。
例如:搜尋’,’是一個特殊字符,在正則表達式中有特殊含義。必需要先轉義。 grep –n ‘\」 regular.txt
|
* | 前面的字符重複0到屢次。
例如匹配ggle,gogle,google,gooogle等等 grep –n ‘go*gle’ regular.txt
|
[list] | 匹配一系列字符中的一個。
例如:匹配gl,gf。 grep –n ‘g[lf]’ regular.txt
|
[n1-n2] | 匹配一個字符範圍中的一個字符。
例如:匹配數字字符 grep –n ‘[0-9]’ regular.txt
|
[^list] | 匹配字符集之外的字符
例如:grep –n ‘[^o]‘ regular.txt 匹配非o字符
|
\{n1,n2\} | 前面的字符重複n1,n2次
例如:匹配google,gooogle。 grep –n ‘go\{2,3\}gle’ regular.txt
|
\<word | 單詞是的開頭。
例如:匹配以g開頭的單詞 grep –n ‘\<g’ regular.txt
|
word\> | 匹配單詞結尾
例如:匹配以tion結尾的單詞 grep –n ‘tion\>’ regular.txt |
擴展正則表達式 egrep:
元數據 |
意義和範例 |
+ | 重複前面字符1到屢次。
例如:匹配god,good,goood等等字符串。 grep –nE go+d’ regular.txt
|
? | 匹配0或1次前面的字符
例如,匹配gd,god grep –nE ‘go?d’ regular.txt
|
| | 或(or)的方式匹配多個字串 例如:grep –nE ‘god|good’ regular.txt
匹配god或者good。
|
() | 匹配整個括號內的字符串,原來都是匹配單個字符
例如:搜尋good或者glad grep –nE ‘g(oo|la)d’ regular.txt |