Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1442978
  • 博文数量: 165
  • 博客积分: 2068
  • 博客等级: 上尉
  • 技术积分: 2102
  • 用 户 组: 普通用户
  • 注册时间: 2011-08-27 16:07
文章分类

全部博文(165)

文章存档

2018年(1)

2017年(22)

2016年(9)

2015年(22)

2014年(8)

2013年(25)

2012年(53)

2011年(25)

分类: 系统运维

2015-10-29 22:07:14

1. 从stdin读取输入 
$ echo -e "this is a word\nnext line" | grep word
2. 在单个文件中搜索文本
chicol@debian:~/scripts/chapter_4$ grep word a.txt 
this is a word
3. 在多个文件中搜索文本
chicol@debian:~/scripts/chapter_4$ grep word a.txt b.txt 
a.txt:this is a word
b.txt:this is another word
4. 用--color选项可以在输出行中加粗显示匹配到的单词
chicol@debian:~/scripts/chapter_4$ grep word --color=auto a.txt b.txt 
a.txt:this is a word
b.txt:this is another word
5. grep -E 匹配模式里可以使用正则表达式,或者用egrep,默认可以使用正则表达式
6. grep -o 只输出文件中匹配到的部分 
chicol@debian:~/scripts/chapter_4$ grep -o word a.txt 
word
7. grep -v打印除匹配到行之外的所有行
8. grep -c 统计匹配到字符串的行数
chicol@debian:~/scripts/chapter_4$ cat matchworld.txt 
text text
text
chicol@debian:~/scripts/chapter_4$ grep -c text matchworld.txt 
2
9. 要统计匹配项的数量,可以用下面的技巧
chicol@debian:~/scripts/chapter_4$ grep -o text matchworld.txt 
text
text
text
chicol@debian:~/scripts/chapter_4$ grep -o text matchworld.txt | wc -l
3
10. grep -n 打印出匹配行的行号
chicol@debian:~/scripts/chapter_4$ grep -n word a.txt 
1:this is a word
11. grep -i 忽略大小写
12. 匹配多个样式
grep -e “pattern1”  -e “pattern2”
13. grep “pattern” -R -n 多级目录下递归搜索文件匹配
14. 在grep搜索中指定或排除文件
grep “pattern” . -r --include *.{c,cpp} 在当前目录递归搜索所有的.c和.cpp文件
grep "pattern" . -r --exclude "README"  在搜索中排除所有的README文件
排除目录用--exclude-dir
15. 打印出匹配文本之前或之后的行
chicol@debian:~/scripts/chapter_4$ seq 10 | grep 5 -A 1  打印匹配文本之后的1行
5
6
chicol@debian:~/scripts/chapter_4$ seq 10 | grep 5 -B 1  打印匹配文本之前的1行
4
5
chicol@debian:~/scripts/chapter_4$ seq 10 | grep 5 -C 1  打印匹配文本前后的1行
4
5
6





阅读(1349) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~