且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

linux shell 脚本之深入浅出的grep的用法

更新时间:2022-10-02 19:20:00

      今天在纠结grep用法时候,由于讲解的教材比较少,纠结了较长的时间。最终还是攻下了,所以拿出来给大家分享。

grep

      显示匹配一个或多个模式的文本行,时常会作为管道后的第一步,以便对匹配上的数据做进一步处理。

最常见用法,查询文件内字符串

[root@localhost /]# grep root /etc/shadow 
root:$1$HFDnk5hm$DSAc4IUls1yUyocXFNQ.A.:15141:0:99999:7::: 
[root@localhost /]#

参数

-E  使用扩展正则表达式进行匹配,使用grep –E 代替传统的扩展正则表达式 egrep

扩展正则表达式和正则表达式的区别:  (-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  使用固定字符串进行匹配 grep –F 取代传统的 fgrep 。 使用正则表达式; 默认情况下 grep 使用的就是正则表达式,grep = grep –F

-e  通常,第一个非选项的参数会指定要匹配的模式,这个模式以-号开头时,grep就会混淆,而-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  列出匹配模式的文件名称  (列出当前目录下含有test字符串的文件)

[root@localhost space]# grep -l 'test' ./* 
./test 
./test2 
[root@localhost space]#

-q  静默模式,如果匹配成功,则grep会离开,不显示匹配。

[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]#


本文转自 郑伟  51CTO博客,原文链接:http://blog.51cto.com/zhengweiit/658252