grep 是Global search Regular Expression的缩写。用于文件的字符串搜索。支持正则表达式。
使用方法:
grep [Options] Pattern FILE[s]
Options常用的有以下:
-c
-i
-l
-n
-v
-e 正则表达式
-w 以单词为单位匹配
-A 显示匹配行和之后的N行
-B 显示匹配行和之前的N行
-C 显示匹配行和之前之后的N行
Pattern:
可使用正则表达式
FILE[s]:
可单个文件,也可多个,也可以是正则表达式的文件。
示例:
测试文本test.txt:
This is the first string.
THIS IS THE SECOND STRING.
third line..
the end;
普通搜索:
$ grep "string" test.txt
This is the first string.
不区分大小写:
$ grep -i "string" test.txt
This is the first string.
THIS IS THE SECOND STRING.
显示行号:
$ grep -i -n "string" test.txt
1:This is the first string.
2:THIS IS THE SECOND STRING.
只显示匹配的行号:
$ grep -i -c "string" test.txt
2
以单词为单位搜索:
$ grep -w "is" test.txt
This is the first string.
$grep "is" test.txt
Thisis the first string.
显示匹配前后的N行:
$ grep -A 2 -w "is" test.txt // 显示匹配之后的2行
This is the first string.
THIS IS THE SECOND STRING.
third line..
$ grep -B 2 -w "end" test.txt // 显示匹配之前的2行
THIS IS THE SECOND STRING.
third line..
the end;
$grep -C 2 -w "IS" test.txt // 显示匹配前后的2行,test.txt总共4行
This is the first string.
THIS IS THE SECOND STRING.
third line..
the end;
反搜索,显示不包括字符串的行
$ grep -n -i -v "this" test.txt
3:third line..
4:the end;
多个不匹配的条件:
$ grep -n -i -v -e "this" -e "the" test.txt
3:third line..
搜索多个文件:
$ grep "include" * // 当前目录下所有含有"include"的文件及匹配行, 加参数-l 只显示文件名
dll.c:#include <stdio.h>
gbtest.c:#include <stdio.h>
redir.txt:#include <stdio.h>
test.c:#include <stdio.h>
|管道作为输入:
$ ls | grep ".c" 搜索当前文件夹下.c文件
dll.c
gbtest.c
test.c
与find命令联合使用:
$ find . -type f -name \*.mk | xargs grep Dialer -in
搜索文件夹下.mk结尾, 并包含Dialer字符串的文件.