码迷,mamicode.com
首页 > 其他好文 > 详细

grep使用

时间:2014-12-29 06:36:43      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:grep使用

########################## grep 使用 ###############
测试数据:
line1: What‘s that smell?
line2: What‘s that noise?
line3: What is this line for?
line4: What are you up to?
line5: May I ask you a question?
line6: What does "drowsy" mean?
line7: What‘s this?
line8: What‘s that?
line9: Who does this belong to?
line10: Which one?

#1 显示匹配this行后再显示2行 (参数 -A)
grep this -A 2 testfile.txt

#2 显示匹配this行周围的2行 (参数 -B)
grep -B 2 this testfile.txt

#3 显示匹配行上下各2行 相当于上面(AB)组合 (参数 -C)
grep -C 2 drowsy testfile.txt

#4 忽略二进制文件搜索 (参数 -I)
grep this -I testfile.txt

#5 显示匹配加颜色 (参数 --colour)
  grep this --colour=auto testfile.txt
  或者
  export GREP_COLOR=‘1;32‘
  grep this --colour=auto testfile.txt  

#6 计算匹配成功多少行 (参数 -c)
   grep -c What testfile.txt

#7 显示过滤掉this 即:显示不匹配的行 (参数 -v)
grep -v ‘this‘ testfile.txt

#8 搜索套接字、管道和销售队列等 (参数 -D ACTION)

#9 正则表达式搜索 (参数 -E) 相当于egrep
grep -E ‘What|May‘ testfile.txt
grep -v -E ‘Wh|this‘ testfile.txt

#10 输出匹配行的同时输出所属文件名 (参数 -H)
grep -H -E ‘this|ye‘ testfile1.txt testfile.txt
grep -HEn ‘this|ye‘ testfile1.txt testfile.txt

#11 输出匹配行的不输出所属文件名 (参数 -h)
grep -E -h ‘this|ye‘   testfile.txt testfile1.txt    

#12 忽略大小写 (参数 -i)
grep wh -i testfile.txt

#13 显示不匹配的文件名(搜索出那些文件不包含匹配yeqing) (参数 -L)
grep yeqing -L testfile*   

#14 显示匹配的文件名 (哪些文件包含匹配 yeqing) (参数 -l)
grep yeqing -l testfile*

#15 搜索最多匹配行(参数 -m)
grep yeqing -m 2  testfile.txt

#16 打印匹配的行号 (参数 -n)
grep Wh -n testfile.txt

#17 只显示匹配的部分
grep -o this testfile.txt

#18 不打印,搜索到返回0 (参数 -q)
grep -q ye testfile1.txt
echo $?

#19 忽略错误信息 (参数 -s)
[root@home-backup scripts]# grep -s sss ss./a
[root@home-backup scripts]# grep  sss ss./a
grep: ss./a: 没有那个文件或目录

 参考资料:

http://www.gnu.org/software/grep/manual/grep.html

http://www.debian-administration.org/articles/460

http://www.regular-expressions.info/posix.html

本文出自 “技术屌丝” 博客,谢绝转载!

grep使用

标签:grep使用

原文地址:http://yeqing.blog.51cto.com/3159086/1597042

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!