案例1:精准匹配(-w)
[root@localhost test]# cat 1.txt | grep root 1.txt --color=auto
1-1.png
[root@localhost test]# cat 1.txt | grep -w "root" 1.txt --color=auto
1-2.png
注: 可以看出来,加
-w
参数会精准匹配要匹配的单词,并且是区分呢大小写匹配。其中 参数--color=auto
是加入自动颜色,就是我们匹配的单词高亮显示
案例2:取反参数(-v)
[root@localhost test]# ps -ef | grep ssh
2-1.png
[root@localhost test]# ps -ef | grep ssh | grep -v grep
2-2.png
案例3:统计出现的行数数量(-c)
[root@localhost test]# grep -c "root" 1.txt
3-1.png
案例4:显示匹配的行数(-n)
[root@localhost test]# grep -n "root" 1.txt --color=auto
4-1.png
案例5:显示匹配的文件(-l)
[root@localhost test]# grep "root" 1.txt 2.txt 3.txt
5-1.png
[root@localhost test]# grep -l "root" 1.txt 2.txt 3.txt
5-2.png
案例6:忽略文件大小写(-i)
[root@localhost test]# cat 1.txt | grep -i "root" --color=auto
6-1.png
案例7:控制字符范围
[root@localhost test]# seq 10 | grep "5" -A 3
7-1.png
[root@localhost test]# seq 10 | grep "5" -B 3
7-2.png
[root@localhost test]# seq 10 | grep "5" -C 3
7-3.png
通过以上图示实验,可以明白:
-A n 向下匹配n行
-B n 向上匹配n行
-C n 同时向上向下匹配n行