(1). $ grep "pattern" filename
(2). 从stdin中读取
[root@master1 test]# echo -e "this is a word\nnext line" | grep word
this is a word
(3). 单个grep对多个文件进行搜索
$ grep "match_text" file1 file2 file3...
(4). --color 在输出中着重标出匹配到的单词
$ grep word filename --color=auto
(5). grep使用正则表达式,需要添加-E选项或者使用egrep
$ grep -E "[a-z]+" filename
或者
$ egrep "[a-z]+" filename
(6). -o 只输出匹配到的文本
$ echo "this is a line." | egrep -o "[a-z]+\."
line. ## \. 匹配字符"."
(7). -v 打印包含match_pattern之外的所有行
$ grep -v match_pattern filename
(8). -c 统计文件或文本中包含匹配字符串的行数,并不是匹配的次数。
$ echo -e "1 2 3 4\nhello\n5 6" | egrep -c "[0-9]"
2
(9). 要统计匹配项的数量,可以使用下面的方式
$ echo -e "1 2 3 4\nhello\n5 6" | egrep -o "[0-9]" | wc -l
6
(10). -n 打印出包含匹配字符串的行数
$ grep -n "pattern" filename
如果涉及多个文件,也会随着输出文件名
$ grep linux -n sample1.txt sample2.txt
sample1.txt:2:linux is fun
sample2.txt:2:planetlinux
(11). -b -o 打印匹配字符串位于的字符或字节偏移
$ echo gnu is not unix | grep -b -o "not"
7:not
从第一个字符算起,起始值为0。not的偏移值是7,也就是说not是从第8个字符开始的。
(12). -l 搜索多个文件并找出匹配文本位于哪个文件中
$ grep -l linux sample1.txt sample2.txt
sample1.txt
sample2.txt
===============================================================================================
1.递归搜索文件
在多级目录中对文本进行递归搜索:
$ grep "text" . -R -n ##命令中的“.” 指定了当前目录
例:$ cd src_dir
$ grep "test_function()" . -R -n
./miscutils/test.c:16:test_function();
test_function()位于miscutils/test.c的第16行
2. -i 忽略样式中的大小写
$ echo hello world | grep -i "HELLO"
hello
3. 用grep匹配多个样式
$ grep -e "pattern1" -e "pattern2"
例: $ echo this is a line of text | grep -e "this" -e "line" -o
this
line
4. 在grep搜索中指定(include)或排除(exclude)文件
目录中递归搜索所有.c和.cpp文件
$ grep "text" . -r --include *.{c,cpp}
搜索中排除所有的README文件
$ grep "text" . -r --exclude "README"
5. 打印匹配文本之前或之后的行
要打印匹配某个结果之后的3行,使用 -A选项:
$ seq 10 | grep 5 -A 3
5
6
7
8
要打印匹配某个结果之前的3行,使用 -B选项:
$ seq 10 | grep 5 -B 3
2
3
4
5
要打印匹配某个结果之前以及之后的3行,使用-C选项:
$ seq 10 | grep 5 -C 3
2
3
4
5
6
7
8