shell编程-正则表达式

1、正则表达式与通配符

  正则表达式用来在文件中匹配符合条件的字符串,正则是包含匹配。grep、 awk、sed等命令可以支持正则表达式。
  通配符用来匹配符合条件的文件名,通配符是完全匹配。ls、find、 cp这些命令不支持正则表达式,所以只能使用shell自己的通配符来进行匹配了。

2、基础正则表达式

在这里插入图片描述
“*”前一个字符匹配0次,或任意多次

#匹配所有内容,包括空白行
[root@localhost sh]# grep "a*" test_rule.txt 
#匹配至少包含有一个a的行
[root@localhost sh]# grep "aa*" test_rule.txt 
匹配最少包含两个连续a的字符串
[root@localhost sh]# grep "aaa*" test_rule.txt 
#则会匹配最少包含四个个连续a的字符串
[root@localhost sh]# grep "aaaaa*" test_rule.txt 

"."匹配除了换行符外任意一个字符

#“s..d”会匹配在s和d这两个字母之间一定有两个字符的单词
[root@localhost sh]# grep "s..d" test_rule.txt 
#匹配在s和d字母之间有任意字符
[root@localhost sh]# grep "s.*d" test_rule.txt 
#匹配所有内容
[root@localhost sh]# grep ".*" test_rule.txt 

“^”匹配行首,"$"匹配行尾

#匹配以大写“M”开头的行
[root@localhost sh]# grep "^M" test_rule.txt 
#匹配以小写“n”结尾的行
[root@localhost sh]# grep "n$" test_rule.txt 
#会匹配空白行
[root@localhost sh]# grep -n "^$" test_rule.txt 

"[^]"匹配除中括号的字符以外的任意一个字符

#匹配不用小写字母开头的行
[root@localhost sh]# grep "^[^a-z]" test_rule.txt 
#匹配不用字母开头的行
[root@localhost sh]# grep "^[^a-zA-Z]" test_rule.txt 

“\”转义符

#匹配使用“.”结尾的行
[root@localhost sh]# grep "\.$" test_rule.txt 

“\{n\}”表示其前面的字符恰好出现n次

#匹配a字母连续出现三次的字符串
[root@localhost sh]# grep "a\{3\}" test_rule.txt 
#匹配包含连续的三个数字的字符串
[root@localhost sh]# grep "[0-9]\{3\}" test_rule.txt 

“\{n,m\}” 匹配其前面的字符至少出现n次,最多出现m次

#匹配在字母s和字母i之间有最少一个a,最多三个a
[root@localhost sh]# grep "sa\{1,3\}" test_rule.txt 

“\{n,\}”表示其前面的字符出现不小于n次

#匹配最少用连续三个数字开头的行
[root@localhost sh]# grep "^[0-9]\{3,\}[a-z]" test_rule.txt 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值