九、Linux三剑客之grep

grep是一个可以利用正则表达式进行全局搜索的工具,区分大小写。

参数介绍

-n 打印行号

-i 不区分大小写

--color 高亮显示

-c 符合条件的总行数

-o 只显示匹配到的关键字,不打印整行,会把每一个匹配到的关键字都单独显示在一行中

-B1 显示符合条件的行同时还显示之前的1行,before之意

-A 显示符合条件的后几行,After之意

-C 显示符合条件的行还会显示之前的n行于之后的n行,-B跟-A的结合,Context上下文之意

-w 搜索的字符串作为一个独立单词才会被匹配,word之意

-v 查找不包含某个字符串的行

-e 匹配多个目标,目标之间“或”关系

-q 使用静默模式,不会输出任何信息,需要配合echo $?命令,如果返回值为0,说明匹配到了目标,如果为1则未匹配到任何字符串

-i 参数案例

[root@tz shell]# grep -i --color test testgrep
zsy 
testTEST
 123

Centos6中没有设置高亮别名,Centos7中默认设置了高亮别名

手动设置高亮别名

[root@tz shell]# alias "grep=grep --color"

-c 参数案例

[root@tz shell]# grep -i test -c testgrep
2

-o 参数案例

有4个123匹配,会输出4行123

[root@tz shell]# grep -i 123 testgrep
TEST 123
abc123abc
123zsy123
[root@tz shell]# grep -i -o 123 testgrep
123
123
123
123

-B 参数案例

-B后面必须要有数字

[root@tz shell]# cat testgrep1
姓名:团子
年龄:18
颜值:自认为爆表,其实爆表

姓名:王尼玛
年龄:30
颜值:带着头套,全靠猜

姓名:王尼美
年龄:18
颜值:貌美如花
[root@tz shell]# grep -B1 "年龄:18" testgrep1
姓名:团子
年龄:18
--
姓名:王尼美
年龄:18

-C 参数案例

[root@tz shell]# grep -C1 "年龄:18" testgrep1
姓名:团子
年龄:18
颜值:自认为爆表,其实爆表
--
姓名:王尼美
年龄:18
颜值:貌美如花

-w 参数案例

[root@tz shell]# grep zsy testgrep
zsy test
zsythink
www.zsythinnk.net
123zsy123
[root@tz shell]# grep -w zsy testgrep
zsy test

-v 参数案例

[root@tz shell]# grep -v -i zsy testgrep

TEST 123
grep Grep
abc
abc123abc

-e 参数案例

[root@tz shell]# grep -e abc -e test testgrep
zsy test
abc
abc123abc

-q 参数案例

[root@tz shell]# grep -q test testgrep
[root@tz shell]# echo $?
0
[root@tz shell]# grep -q 123123123 testgrep
[root@tz shell]# echo $?
1

学习来自朱双印朱老师的博客

博客很赞,通俗易懂

今天的学习是为了以后的工作更加的轻松!
原文地址:https://www.cnblogs.com/tz90/p/12823233.html