grep,是一种强大的文本搜索工具,英文全称为(global search regular expression(RE) and print out the line),意为全面搜索正则表达式并把行打印出来。它能使用正则表达式搜索文本,并把匹配的行打印出来。
【选项】
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
-c 计算找到"搜索字符串"的次数
-o 仅显示出匹配regexp的内容(用于统计出现在文中的次数)
-i 忽略大小写
-n 在行首显示行号
-v 反向选择,即显示不包含"搜索字符串"内容的那一行
-E 扩展的grep,即egrep
--color=auto 以特定颜色高亮显示匹配出的关键的
-A after的意思,显示出匹配字符串机器后n行的数据
-B before的意思,显示匹配字符串及其前n行的数据
-C 显示匹配字符串机器前后各n行
-r 递归搜索
-e 制动多个匹配样式
-q 不显示任何信息。
-w 只显示全字符合的列。
|
【file文件内容】
1
2
3
4
5
6
7
|
[root@test1 test]# cat file
1
2 The world is not you can do, but you should.
3 Life is not easy for any of us.
4 We must work hard.12345678
5 we hope that we can see you soon
6
|
【常见用法举例】
1.排除指定内容
1
2
3
4
5
6
|
[root@test1 test]# grep -v We file
1
2 The world is not you can do, but you should.
3 Life is not easy for any of us.
5 we hope that we can see you soon
6
|
2.统计We出现的次数
1
2
|
[root@test1 test]# grep -c We file
1
|
3.统计单词"we"出现的次数,不区分大小写
1
2
|
[root@test1 test]# grep -ci We file
2
|
4.仅输出匹配到的内容
[root@test1 test]# grep -oi life file
Life
5.在行首显示行号
[root@test1 test]# grep -ni life file
3:3 Life is not easy for any of us.
6.使用正则表达式-E选项
[root@test1 test]# grep -E "[1-9]+" file
1
2 The world is not you can do, but you should.
3 Life is not easy for any of us.
4 We must work hard.12345678
5 we hope that we can see you soon
6
7.匹配多个样式
法一:利用egrep
[root@test1 test]# egrep -i --color=auto "we|life" file
3 Life is not easy for any of us.
4 We must work hard.12345678
5 we hope that we can see you soon
法二:利用-e选项
[root@test1 test]# grep -ie "we" -ie "life" file
3 Life is not easy for any of us.
4 We must work hard.12345678
5 we hope that we can see you soon
8.-q静默输出
1
2
3
|
[root@test1 test]# grep -q we file ;echo $?
0
#不会输出任何信息,如果命令运行成功返回0,失败则返回非0值。一般用于条件测试。
|
9.打印出匹配文本之前或者之后的行
1)显示匹配某个结果之后的3行,使用 -A 选项
[root@test1 test]# grep "3" -A 3 file
3 Life is not easy for any of us.
4 We must work hard.12345678
5 we hope that we can see you soon
6
2)显示匹配某个结果之前的3行,使用 -B选项
[root@test1 test]# grep "5" -B 3 file
1
2 The world is not you can do, but you should.
3 Life is not easy for any of us.
4 We must work hard.12345678
5 we hope that we can see you soon
可以看到,输出中多了第一行,可使用-w选项精确匹配字符,只输出第五行及其前三行,即2-5行。
[root@test1 test]# grep -w "5" -B 3 file
2 The world is not you can do, but you should.
3 Life is not easy for any of us.
4 We must work hard.12345678
5 we hope that we can see you soon
3)显示匹配某个结果的前三行和后三行,使用 -C 选项
[root@test1 test]# grep -w "4" -C 2 file
2 The world is not you can do, but you should.
3 Life is not easy for any of us.
4 We must work hard.12345678
5 we hope that we can see you soon
6
本文转自 xoyabc 51CTO博客,原文链接:http://blog.51cto.com/xoyabc/1684516,如需转载请自行联系原作者