红联Linux门户
Linux帮助

grep命令用法

发布时间:2015-08-09 15:38:12来源:linux网站作者:linux人

1、grep家族

grep: Global search Regular Expression(RE) and Print out the line
grep家族包括grep、egrep和fgrep,egrep和fgrep和grep只有很小的不同。
egrep是grep的扩展,支持更多的元字符,等效于grep -E。
fgrep是fixed grep, 或fast grep,它不识别任何正则表达式,所有的字符都表示它自己,等效于grep -F。


2、grep支持的元字符集

支持正则表达式基本元字符集和附加元字符集。
另外,还支持grep扩展元字符集,主要的有:

w  文字和数字字符,即[A-Za-z0-9]  Lw*e  匹配一个L字符,紧跟着0个或者多个文字或数字字符,然后是e
W  非文字和数字字符,即[^A-Za-z0-9],和w相反
+  匹配1个或多个先前字符  [a-z]\+ove  匹配一个小写字符且后面是ove的。
?  匹配0个或1个先前字符
a|b|c  匹配a或b或c  hate|love


3、egrep

在GNU grep(grep -G)里,如果在字符前面加一个反斜杠,这个字符就被翻译成扩展正则表达式,就像egrep和grep -E一样。
$egrep 's(h|u)' datafile

$grep -E 's(h|u)' datafile

$grep 's(h|u)' datafile

例外:单词锚定符号< >,无论什么grep,都必须加反斜杠
$grep '<north>' datafile
$grep -E '<north>' datafile
$egrep '<north>' datafile
$grep -w 'north' datafile


4、grep选项

-c   只显示匹配行的数量
-i   忽略大小写
-n   打印行号
-s   静默工作,不显示错误信息
-q   静默工作,不显示查找结果
-v   只显示不匹配的行
-w   等效于< >


5、例子

1)在一个或多个文件中查找字符串
#grep "hello,world" ./hello1.txt ./hello2.txt

2)查找Summary信息
#../gcc-4.4.1/contrib/test_summary|grep -A7 Summary
查找带有Summary的行,同时显示该行后面7行,这种用法用于显示一些测试结果中的summary信息。

3)递归查找目录
#grep -R 'typedef struct page {' ./

4)翻转查找结果
#grep -v  deinstall //查找不包含deinstall的行


14个grep命令的例子:http://www.linuxdiyf.com/linux/12212.html

Linux下grep命令用法实例教程:http://www.linuxdiyf.com/linux/9876.html

Linux/Unix下grep命令使用的几个例子[grep Examples]:http://www.linuxdiyf.com/linux/3265.html

误删文件不用怕 grep命令帮你恢复:http://www.linuxdiyf.com/linux/67.html

使用grep命令快速定位代码位置:http://www.linuxdiyf.com/linux/9276.html