grep的使用方法

今天被同事问到了如何用grep进行全词匹配,通常用到的都是模糊查询,通过度娘,用了下面的汇总code

grep 语法ip

grep 'word' filename
grep 'string1 string2'  filename
cat otherfile | grep 'something'
command | grep 'something'
command option1 | grep 'data'
grep --color 'data' fileName

基本的用法 在某个文件里搜索error字符串字符串

$ grep "error" log.txt

忽略大小写搜索(-i)string

$ grep -i "ErroR" log.txt

全部子目录下的搜索(-r)pip

$ grep -r "exception" log.txt

全字匹配搜索(-w) 若是你搜索boo,查询结果可能包含fooboo,boo123, booooom,等等,能够使用**-w来限定全字匹配**io

$ grep -w "boo" /path/to/file

全字匹配搜索两个不一样单词test

$ grep -w 'word1|word2' /path/to/file

统计字符串出现的次数(-c)file

$ grep -c 'word' /path/to/file

另外加-n的话, 会在结果中,列出匹配字符串的序列号,而且会列出内容搜索

$ grep -n 'word' /path/to/file

列出“不”包含字符串的行(-v)exception

$ grep -v bar /path/to/file

只列出文件名(-l)

$ grep -l 'main' *.pls

高亮显示(--color)

$ grep --color sucre /var/log/vm/test.log

UNIX / Linux pipes + grep

ls -l | grep -i xyz

ls 列出当前目录下的文件和文件夹,| 是管道传递给后面的一个程序,grep再是进行模式匹配

ls *.pls | grep -i --color "AA"
相关文章
相关标签/搜索