天天看點

grep指令

準備test檔案,内容如下:

grep指令

dlf test

dlfthink

www.baidu.com

TEST 123

Dlf's lemon

grep Grep

abc

abc123abc

123dlf123

[www.baidu.com]

1)      grep -i "test" test.txt  搜尋出含有“test” 字元串(-i:不區分大小)

grep指令

2)      grep -i -n "test" test.txt  搜尋出含有“test” 字元串(-i:不區分大小),并列印行号

grep指令

3)      grep -i -n --color "test" test.txt  搜尋出含有“test” 字元串(-i:不區分大小),并列印行号,關鍵字“test”顔色标記(centos7系統預設為grep指令配置了别名,是以不使用—color也能顯示顔色)

grep指令

4)      grep -I -c "test" test.txt,列印“test”字元串(不區分大小寫)顯示的次數

grep指令

5)      grep -I -o "test" test.txt,列印“test”字元串(不區分大小寫),但不列印整行

grep指令

test2.txt檔案内容如下:

grep指令

6)      grep -A1 “18” test2.txt,列印“18”字元串和它上一行的資訊

grep指令

7)      grep -B1 “18” test2.txt,列印“18”字元串和它下一行的資訊

grep指令

8)      grep -C1 “18” test2.txt,列印“18”字元串和它上一行和下一行的資訊

grep指令

9)      grep -w "dlf" test.txt,精确比對出“dlf”字元串的

grep指令

10)   grep -v "dlf" test.txt,比對出不包含“dlf”字元串的行

grep指令

11)   grep -e 'abc' -e 'dlf' test.txt,同時比對”abc”和”test”字元串

grep指令

12)   grep -q 靜默模式

靜默模式下grep不會輸入任何資訊,無論是否比對到指定的字元串,都不會輸出任何資訊,是以配合使用“echo %?”指令,檢視指令的執行狀态,如果傳回值0,證明上一條grep指令比對到了指定的字元串,如果傳回值1,則證明上一條grep指令沒有比對到指定的字元串。

grep指令

參考來源

http://www.zsythink.net/archives/1733