grep
最常见用法,查询文件内字符串
[root@localhost /]# grep root /etc/shadow
root:$1$HFDnk5hm$DSAc4IUls1yUyocXFNQ.A.:15141:0:99999:7:::
[root@localhost /]#
参数
-E
扩展正则表达式和正则表达式的区别:
+
匹配一个或多个先前的字符
[root@localhost space]# touch test
[root@localhost space]# vim test
aaaredhat
bbbredhat
yyyredhat
zzzredhat
redhataaa
redhatbbb
redhatyyy
redhatzzz
:wq
[root@localhost space]# cat test|grep –E '[a-h]+redhat'
aaaredhat
bbbredhat
[root@localhost space]#
[root@localhost space]# cat test|grep -E 'redhat+[h-z]'
redhatyyy
redhatzzz
[root@localhost space]#
当去掉-E选项的时候,正则表达式是不支持这样查询的。
[root@localhost space]# cat test|grep 'redhat+[a-z]'
[root@localhost space]#
?
匹配零个或多个先前的字符
[root@localhost space]# cat test|grep -E 'r?aaa'
aaaredhat
redhataaa
[root@localhost space]# cat test|grep 'r?aaa'
[root@localhost space]#
a|b|c
匹配a或b或c
[root@localhost space]# cat test|grep -E 'b|z'
bbbredhat
zzzredhat
redhatbbb
redhatzzz
[root@localhost space]# cat test|grep 'b|z'
[root@localhost space]#
() 分组符号
[root@localhost space]# cat test|grep -E 'redha(tz|ta)'
redhataaa
redhatzzz
[root@localhost space]# cat test|grep 'redha(tz|ta)'
[root@localhost space]#
x{m} 重复字符x,至少m次
(如果用正则表达式,格式为x\{m,\})
[root@localhost space]# cat test|grep -E 'a{3}'
aaaredhat
redhataaa
[root@localhost space]# cat test|grep 'a\{3,\}'
aaaredhat
redhataaa
[root@localhost space]#
-F
-e
[root@localhost space]# cat test|grep -e '-test'
-test
[root@localhost space]# cat test|grep '-test'
grep:无效选项 -- t
Usage: grep [OPTION]... PATTERN [FILE]...
Try `grep --help' for more information.
[root@localhost space]#
-i
[root@localhost space]# cat test|grep -i test
-test
-TEST
[root@localhost space]#
-l
[root@localhost space]# grep -l 'test' ./*
./test
./test2
[root@localhost space]#
-q
[root@localhost space]# grep test ./test
-test
[root@localhost space]# grep -q test ./test
[root@localhost space]#
-s
-v
[root@localhost space]# cat test|grep test
-test
[root@localhost space]# cat test|grep -v test
-TEST
[root@localhost space]#
本文出自 “MVP - Torrent的博客” 博客,请务必保留此出处http://zhengweiit.blog.51cto.com/1109863/658252