案例1:精准匹配(-w)
1
| [root@localhost test]# cat 1.txt | grep root 1.txt --color=auto
|

1
| [root@localhost test]# cat 1.txt | grep -w "root" 1.txt --color=auto
|

注: 可以看出来,加-w
参数会精准匹配要匹配的单词,并且是区分呢大小写匹配。其中 参数--color=auto
是加入自动颜色,就是我们匹配的单词高亮显示
案例2:取反参数(-v)
1
| [root@localhost test]# ps -ef | grep ssh
|

1
| [root@localhost test]# ps -ef | grep ssh | grep -v grep
|

案例3:统计出现的行数数量(-c)
1
| [root@localhost test]# grep -c "root" 1.txt
|

案例4:显示匹配的行数(-n)
1
| [root@localhost test]# grep -n "root" 1.txt --color=auto
|

案例5:显示匹配的文件(-l)
1
| [root@localhost test]# grep "root" 1.txt 2.txt 3.txt
|

1
| [root@localhost test]# grep -l "root" 1.txt 2.txt 3.txt
|

案例6:忽略文件大小写(-i)
1
| [root@localhost test]# cat 1.txt | grep -i "root" --color=auto
|

案例7:控制字符范围
1
| [root@localhost test]# seq 10 | grep "5" -A 3
|

1
| [root@localhost test]# seq 10 | grep "5" -B 3
|

1
| [root@localhost test]# seq 10 | grep "5" -C 3
|

通过以上图示实验,可以明白:
-A n 向下匹配n行
-B n 向上匹配n行
-C n 同时向上向下匹配n行