1. 程式人生 > >Linux 學習總結(十九)正則三劍客之grep

Linux 學習總結(十九)正則三劍客之grep

grep

grep
過濾器,egrep可以理解為grep的升級版
1 格式:grep [-cinvABC] ‘word‘ filename
-c:統計符合要求的行數
例如 : grep -c ‘root‘ /etc/passwd
grep -c ‘‘ /etc/passwd 統計文件總行數
-i:忽略大小寫
-n:行號輸出
grep -n ‘root‘ /etc/passwd
-v 打印不符合要求的行, 補集
-An 打印符合要求的行同時帶上下面n行,n為數字
-Bn 打印符合要求的同時帶上上面n行
-Cn 打印符合要求的同時上下都帶上n行
附上-c ,-n ,-v的運行結果
grep ‘root‘ -c /etc/passwd;grep ‘‘/etc/passwd -c

技術分享圖片
head /etc/passwd |grep ‘root‘ -n
技術分享圖片
head -3 /etc/passwd |grep ‘root‘ -nv
技術分享圖片
舉例:
grep 結合正則表達式的例子:
技術分享圖片
2 過濾出所有帶數字的行
grep ‘[0-9]‘ test.txt -n
技術分享圖片
3 過濾出以#好開頭的行
grep ‘^#‘ test.txt -n
技術分享圖片
重新編輯test.txt.
技術分享圖片
4 過濾出非純數字的行
grep ‘[^0-9]‘ test.txt
符號^放進[]裏面表示非的意思,放在[]外面表示以某個字符開頭例如:
技術分享圖片
5 過濾出非數字開頭的行
grep ‘^[^0-9]‘ test.txt
技術分享圖片
7 對上命令取反過濾出以數字開頭的行
grep -v ‘^[^0-9]‘ test.txt

技術分享圖片
該命令相當於 grep ‘^[0-9]‘ test.txt
重新編輯test.txt
技術分享圖片
8 . 點 字符 匹配任意一個字符
grep ‘r.t‘ test.txt
技術分享圖片
9 * 匹配之前的項0次或多次
grep ‘r\*t‘ test.txt
技術分享圖片
10 .* 組合起來,就是匹配所有字符
技術分享圖片
以下列舉的正則符號均不能直接用grep,需要加-E選項,或者給符號加轉義字符,為了方便我們直接使用egrep
11 {n} 匹配之前的項n次,
{n,} 匹配之前的項n次及其以上
{n,m} 指定之前的項所需匹配的最小次數和最大次數
egrep ‘r{2}t‘ test.txt
egrep ‘r{2,}t‘ test.txt
egrep ‘r{1,2}t‘ test.txt

技術分享圖片
12 + 匹配之前的項1次或多次,*是從0次開始,+是從1次開始
egrep ‘r+t‘ test.txt
技術分享圖片
13 ? 匹配之前的項0次或1次
egrep ‘r?t‘ test.txt
技術分享圖片
14 | 匹配|兩邊的任意一項
egrep ‘root|rt’ test.txt
技術分享圖片
或者 egrep ‘r(t|o)‘ test.txt
技術分享圖片
以上()創建了一個用於匹配的字符串

Linux 學習總結(十九)正則三劍客之grep