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