Linux基礎grep、egrep和fgrep
阿新 • • 發佈:2019-01-01
grep、egrep和fgrep簡介
三者之間的關係:grep -E 等同於 egrep,grep -F 等同於 fgrep。
命令 | 是否支援正則 | 支援的正則型別 |
---|---|---|
grep | ☑️ | 基本正則表示式 |
egrep | ☑️ | 擴充套件正則表示式 |
fgrep | ✖️ |
grep簡單示例
-> cat data4.txt This is line number 1. This is line number 2. This is line number 3. This is line number 4. This is line number 11. This is line number 6 # “--color”選項會將數字“1”和“11”會以紅色標記出來 -> grep --color "1" data4.txt This is line number 1. This is line number 11. # 管道的方式也可以實現和上面一樣的效果 —> cat data4.txt | grep --color "1" This is line number 1. This is line number 11. # "-v"選項實現反查效果 —> cat data4.txt | grep -v "1" This is line number 2. This is line number 3. This is line number 4. This is line number 6 -> cat -n data4.txt 1 This is line number 1. 2 This is line number 2. 3 This is line number 3. 4 This is line number 4. 5 This is line number 11. 6 This is line number 6 # "-n"選項顯示行號 -> cat data4.txt | grep -n --color "1" 1:This is line number 1. 5:This is line number 11. # "-c"選項顯示到底搜尋了多少行 -> cat data4.txt | grep -c "1" 2 # "-i"選項可以實現不區分字母的大小寫 -> grep "this" data4.txt -> grep -i "this" data4.txt This is line number 1. This is line number 2. This is line number 3. This is line number 4. This is line number 11. This is line number 6
grep環顧四周
-> cat data5.txt This is line number 1. This is line number 2. This is line number 3. This is line number 4. This is line number 5. This is line number 6. # "-A"選項是指目標資料下面的若干行,是After的縮寫。“-A 1”表示展示匹配行下面一行的內容。 -> grep -A 1 5 data5.txt This is line number 5. This is line number 6. # "-B"選項是指目標資料前面的若干行,是Before的縮寫。“-B 1”表示展示匹配行上面一行的內容。 -> grep -B 1 5 data5.txt This is line number 4. This is line number 5. # "-C"選項,是“-A”和“-B”選項的合體,除了展示匹配行之外,還展示出匹配行上面和下面各若干行。 # 示例中“-C 2”展示匹配行上面2行和下面2行的內容,最大行才6,所以只能展示到6了。 -> grep -C 2 5 data5.tx This is line number 3. This is line number 4. This is line number 5. This is line number 6.
grep處理多個檔案
-> cat test1.txt
first
-> cat test2.txt
first second
-> cat test3.txt
third
# "-l"選項實現在多個檔案中查詢,返回檔名
-> grep -l "first" *.txt
test1
test2
# "-L"選項實現反向操作
-> grep -L "first" *.txt
test3
grep中詞的含義
-> cat test4 I love you. My gloves are red. # 在grep中,詞一般是由字母、數字和下劃線組成的,且詞與詞之間通常使用空格、製表符(tab)或換 # 行符(\n)分隔,所以查出來的結果不是我們所要的 -> grep love test4 I love you. My gloves are red. # "-w"選項實現這個功能 -> grep -w love test4 I love you. # “<>”也可以實現這個功能,需要新增“\” -> grep ' \<love\>' test4 I love you.
grep查詢中的特殊字元的處理
-> cat test5.
This is a nice $&#^test.
-> grep '^test' test5
# 在fgrep眼裡沒有特殊字元,都是普通字元
-> fgrep '^test' test5
This is a nice $&#^test.