linux shell 脚本之深入浅出的grep的用法
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了linux shell 脚本之深入浅出的grep的用法,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2424字,纯文字阅读大概需要4分钟。
内容图文
今天在纠结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]#
原文:http://www.cnblogs.com/xiaofeng028/p/3526088.html
内容总结
以上是互联网集市为您收集整理的linux shell 脚本之深入浅出的grep的用法全部内容,希望文章能够帮你解决linux shell 脚本之深入浅出的grep的用法所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。