grep命令可以检索文件中包含关键字(可以使用正则)的行,默认区分大小写。
[email protected]:~/test$ cat test.txt this is linux this is Linux this is mysql this is Mysql [email protected]:~/test$ grep ‘linux‘ test.txt this is linux [email protected]:~/test$ grep ‘Mysql‘ test.txt this is Mysql [email protected]:~/test$
使用 -c 参数,获取包含关键字的行数
[email protected]:~/test$ grep -c ‘is‘ test.txt 4 [email protected]:~/test$ grep -c ‘sql‘ test.txt 2 [email protected]:~/test$
使用 -n 参数,打印内容的同时,显示所在的行号
[email protected]:~/test$ cat test.txt this is linux this is Linux this is mysql this is Mysql [email protected]:~/test$ grep -n ‘mysql‘ test.txt 3:this is mysql [email protected]:~/test$
使用 -i 参数,查找时,不区分大小写
[email protected]:~/test$ grep -i ‘mysql‘ test.txt this is mysql this is Mysql [email protected]:~/test$
使用 -v 参数,查找不包含关键字的行
[email protected]:~/test$ cat test.txt this is linux this is Linux this is mysql this is Mysql [email protected]:~/test$ grep -v ‘Linux‘ test.txt this is linux this is mysql this is Mysql [email protected]:~/test$
要想使用正则表达式,可以使用 -E 参数
shell正则和perl语言的正则类似,基本通用。
[email protected]:~/test$ cat test.txt this is linux this is Linux that are apples [email protected]:~/test$ grep -E ‘^that‘ test.txt #以that开头的行 that are apples [email protected]:~/test$ grep -E ‘Linux$‘ test.txt #以Linux结尾的行 this is Linux [email protected]:~/test$ grep -E ‘.inux‘ test.txt # ‘.‘表示任意一个字符(不包含空白) this is linux this is Linux [email protected]:~/test$ grep -E ‘p*‘ test.txt # ‘*’表示前面一个字母出现0,1或任意多次 this is linux this is Linux that are apples [email protected]:~/test$ grep -E ‘.+p.+‘ test.txt # ‘+’表示前面一个字母出现1或任意多次 that are apples that are apples [email protected]:~/test$ grep -E ‘p{2}‘ test.txt # {n}前面的一个字符出现n次 that are apples [email protected]:~/test$
还有一些常用的匹配模式,比如 ‘^$‘表示一个空行 ; ‘^.$‘表示只有一个字符的行 ; 使用 \ 来转义,比如使用\.来匹配一个点 ; [0-9]表示匹配一个数字 ; [a-z]|[A-Z]表示任意一个字母; 使用|表示‘或’ ;
[email protected]:~/test$ echo ‘ip is 192.168.1.1‘ > test.txt [email protected]:~/test$ grep -E ‘([1-9][0-9]*\.){3}[1-9][0-9]*‘ test.txt ip is 192.168.1.1 [email protected]:~/test$