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

今天在纠结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]#

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值