> Linux命令 >

Linux/Unix下grep命令使用的几个例子 grep Examples

grep 语法
grep 'word' filenamegrep 'string1 string2'  filenamecat otherfile | grep 'something'command | grep 'something'command option1 | grep 'data'grep --color 'data' fileName
 
 
基本的用法
在某个文件里搜索error字符串
$ grep "error" log.txt
 
 
 
忽略大小写搜索(-i)
$ grep -i "ErroR" log.txt
 
 
 
所有子目录下的搜索(-r)
$ grep -r "exception" log.txt
 
 
 
全字匹配搜索(-w)
如果你搜索boo,查询结果可能包含fooboo,boo123, booooom,等等,可以使用-w来限定全字匹配
$ grep -w "boo" /path/to/file
 
 
 
全字匹配搜索两个不同单词
$ grep -w 'word1|word2' /path/to/file
 
 
 
统计字符串出现的次数(-c)
$ grep -c 'word' /path/to/file
 
另外加-n的话, 会在结果中,列出匹配字符串的序列号,并且会列出内容
$ grep -n 'word' /path/to/file
 
 
 
列出“不”包含字符串的行(-v)
$ grep -v bar /path/to/file
 
 
 
 
只列出文件名(-l)
$ grep -l 'main' *.pls
 
 
 
高亮显示(--color)
$ grep --color oracle /etc/passwd
 
 
 
 
UNIX / Linux pipes + grep 
ls -l | grep -i xyz
 
ls 列出当前目录下的文件和文件夹,| 是管道传递给后面的一个程序,grep再是进行模式匹配
 
例如:ls *.pls | grep -i --color "MM"
 
 
 
 
(责任编辑:IT)