grep就是从文件找到符合正则的一些行。这个命令来源于ed编辑器常用g/re/p这个命令来做类似的功能。
基本的语法
grep 'word' filename
grep 'string1 string2' filename
cat otherfile | grep 'something'
command | grep 'something'
grep 'string1 string2' filename
cat otherfile | grep 'something'
command | grep 'something'
不加任何参数
$ grep boo /etc/passwd
忽略大小写,找到Boo,boo,BOO...所有的
$ grep -i "boo" /etc/passwd
在指定目录下递归的查找
$ grep -r "192.168.1.5" /etc/
只搜索单词,这样booboo就不会被匹配
$ grep -w "boo" /path/to/file
使用egrep等价于grep -E,来支持正则
$ egrep -w 'word1|word2' /path/to/file
使用fgrep等价于grep -F,只支持字符串,不识别任何正则表达式的特殊字符
$ fgrep -w "boo" /path/to/file
同时给出匹配的行数
$ grep -c 'word' /path/to/file
同时给出匹配的行号
$ grep -n 'word' /path/to/file
同时给出说有不匹配的行
$ grep -v bar /path/to/file
使用管道
$ dmesg | egrep '(s|h)d[a-z]'
$ cat /proc/cpuinfo | grep -i 'Model'
$ cat /proc/cpuinfo | grep -i 'Model'
同时给出匹配的文件列表
$ grep -l 'main' *.c
用颜色高亮匹配
$ grep --color vivek /etc/passwd