linux shell脚本中 =~ 的作用
linux shell脚本中 =~ 的作用
=~ 表示正则表达式左侧是否匹配右侧。
001、举例如下:
[root@pc1 test1]# str1=12343 ## 纯数字字符串 [root@pc1 test1]# str2=abdef ## 字母字符串 [root@pc1 test1]# str3=132ds ## 数字加字母字符串 [root@pc1 test1]# [[ $str1 =~ [0-9]+ ]] [root@pc1 test1]# echo $? ## 纯数字,返回0 0 [root@pc1 test1]# [[ $str2 =~ [0-9]+ ]] ## 纯字母,返回1 [root@pc1 test1]# echo $? 1 [root@pc1 test1]# [[ $str3 =~ [0-9]+ ]] ## 匹配至少1个数字,返回0 [root@pc1 test1]# echo $? 0 [root@pc1 test1]# [[ $str3 =~ [0-9]+$ ]] ## 必须全部是数字,返回1 [root@pc1 test1]# echo $? 1

002、测试2
[root@pc1 test1]# str1=12343 [root@pc1 test1]# str2=abdef [root@pc1 test1]# str3=132ds [root@pc1 test1]# [[ $str1 =~ [a-z]+$ ]] ## 匹配字母一直到最后,匹配失败,返回1 [root@pc1 test1]# echo $? 1 [root@pc1 test1]# [[ $str2 =~ [a-z]+$ ]] ## 匹配成功,返回0 [root@pc1 test1]# echo $? 0 [root@pc1 test1]# [[ $str3 =~ [a-z]+$ ]] ## 匹配成功, 返回0 [root@pc1 test1]# echo $? 0 [root@pc1 test1]# [[ $str3 =~ ^[a-z]+$ ]] ## 匹配失败, 返回1 [root@pc1 test1]# echo $? 1

。
003、测试3
[root@pc1 test1]# str1=12343 [root@pc1 test1]# str2=abdef [root@pc1 test1]# str3=132ds [root@pc1 test1]# [[ $str1 =~ [a-Z]+[0-9]+ || $str1 =~ [0-9]+[a-z]+ ]] ## str为出数字 [root@pc1 test1]# echo $? 1 [root@pc1 test1]# [[ $str2 =~ [a-Z]+[0-9]+ || $str2 =~ [0-9]+[a-z]+ ]] ## str2为纯字母 [root@pc1 test1]# echo $? 1 [root@pc1 test1]# [[ $str3 =~ [a-Z]+[0-9]+ || $str3 =~ [0-9]+[a-z]+ ]] ## str3为数字加字母 [root@pc1 test1]# echo $? 0

。

浙公网安备 33010602011771号