grep (缩写来自Globally search a Regular Expression and Print)是一种强大的文本搜索工具,它能使用特定模式匹配(包括正则表达式)搜索文本,并默认输出匹配行。
语法 Usage: grep [OPTION]... PATTERNS [FILE]...
例子:
![](https://img-blog.csdnimg.cn/img_convert/91920d64b3d59cd55eac77ad5de896b9.png)
这是一个简单的文件,里面一些简单的内容。
输出hello 所在行的内容
![](https://img-blog.csdnimg.cn/img_convert/1c6e4996db398de0ac420fbc99331f69.png)
grep 'hello' testsimplegrep.txt
忽略大小写输出带有hello的行
grep -i 'hello' testsimplegrep.txt
![](https://img-blog.csdnimg.cn/img_convert/f88f3ceb759241cd5cbf49145395331c.png)
Pattern selection and interpretation(可选的模式以及解释)
![](https://img-blog.csdnimg.cn/img_convert/732ce5258e6974fdf8b233abf44d183f.png)
-E 和 -e:
-e 只能传递一个参数,如果需要传递多个参数需要些多次-e
例如: grep -e 'HELLO' -e 'test' testsimplegrep.txt
![](https://img-blog.csdnimg.cn/img_convert/1523b93a26b0789be74494f0d83423d8.png)
如果使用-E, 多个参数之间用|隔开即可
语法: grep -E 'HELLO|test|linux' testsimplegrep.txt | 表示或者 (or) 的意思
![](https://img-blog.csdnimg.cn/img_convert/ef98fed9ddd00512e1a547993acfbb16.png)
grep -F的使用:
查看文件内容如下
![](https://img-blog.csdnimg.cn/img_convert/47f467c745591e792e5e1f1530f561ec.png)
grep -F 表示将grep命令视为使用固定字符串(fixed strings)而不是正则表达式来匹配模式。在这种模式下,grep会按照严格的文本匹配进行搜索,而不是使用正则表达式中的特殊字符。这通常比正则表达式更快速。
在使用-F选项时,需要注意模式字符串中不能包含正则表达式的元字符,例如圆括号、星号等。grep会将模式字符串视为普通文本来匹配。
先来看一下用-E 的结果:grep -E 'test|rege' testsimplegrep.txt
![](https://img-blog.csdnimg.cn/img_convert/9c94e6fb2495c530b4eb83346e8fc76e.png)
再来看下-F 的结果: grep -F 'test|rege' testsimplegrep.txt
![](https://img-blog.csdnimg.cn/img_convert/2f39af16e563a6ba0b9fbc396441adb9.png)
-i:忽略大小写
grep -i 'linux' testsimplegrep.txt, 看到大写LINUX 和小写linux 都查出来了
![](https://img-blog.csdnimg.cn/img_convert/5c3c610fd2254ba02a01330b7e266c5c.png)
-n:显示关键字所在的行
grep -n 'linux' testsimplegrep.txt
![](https://img-blog.csdnimg.cn/img_convert/fc09f6061641e7b74a4f26ea5122418e.png)
-c: 显示关键字显示的次数
grep -c 'linux' testsimplegrep.txt
![](https://img-blog.csdnimg.cn/img_convert/0c573b187fca0cb76ec48198f5f0bd99.png)
Context control:
-B, --before-context=NUM print NUM lines of leading context
-A, --after-context=NUM print NUM lines of trailing context
-C, --context=NUM print NUM lines of output context
用于在给定文件或文件集中搜索模式或文本字符串,并显示包含该模式的行以及指定数量的匹配行之前的行数。
grep 命令的 -B 选项表示“before(之前)”,并指定在匹配行之前要显示多少行。
grep -i 'unix-type' testsimplegrep.txt -B 1
![](https://img-blog.csdnimg.cn/img_convert/f297ddc125c404892051c2d0135d1f71.png)
当B = 1时,查询结果后多显示1行,当B =2 时,查询结果后多显示俩行。
![](https://img-blog.csdnimg.cn/img_convert/cffce0fcf10c0729ba0f65bdaa374b02.png)
-A (after)同理,显示结果后,往后显示n行;
![](https://img-blog.csdnimg.cn/img_convert/22e27cfcfb17fbca60a287269817ec0e.png)
-C 是从查询到的结果,上下文显示n行
grep -n -i 'unix-type' testsimplegrep.txt -C 1: 上线文显示1行
grep -n -i 'unix-type' testsimplegrep.txt -C 2 上线文显示2行
![](https://img-blog.csdnimg.cn/img_convert/070597822185cb91452a076621ca51c9.png)