大家好,欢迎来到IT知识分享网。
转载说明:如果您喜欢这篇文章并打算转载它,请私信作者取得授权。感谢您喜爱本文,请文明转载,谢谢。
前言
expr (evaluate expressions的缩写)命令是一个手工命令行计数器,既可以用于整数运算,也可以用于相关字符串长度、匹配等的运算处理。
当使用expr计算时,需注意这三点:
1. 运算符及用于计算的数字左右都至少有一个空格;
2. 参与运算的数字必须是整数,不能是小数;
3. 遇到特殊字符需要加上转义符号\。例如乘法运算,因*在shell中有另外的含义,因此*需加上转义符号;
使用场景
1. expr用于直接计算
用expr直接用于加减乘除计算:
[root@test101 ~]# expr 1 + 3 4 [root@test101 ~]# expr 10 - 3 7 [root@test101 ~]# expr 10 \* 2 #注意,乘法这里要加上转义符号 20 [root@test101 ~]# expr 10 / 2 5 [root@test101 ~]#
2. expr配合变量计算
在shell中,expr可用于配合变量进行计算,但注意需要使用反引号将计算表达式括起来,例如:
[root@test101 tmp]# cat test.sh #!/bin/bash a=10 b=`expr $a \* 6` # 注意这里加反引号 echo $b [root@test101 tmp]# [root@test101 tmp]# sh test.sh 60 [root@test101 tmp]#
3. 使用expr判断变量或字符串是否为整数
使用expr判断整数的原理:利用了参与expr计算的数字必须是整数,否则会报错。则可以将需要判断的数字、字符串与一个整数相加,使用expr计算结果,如果目标数字/字符串是整数,则会运行成功,反之则会报错。运行结果使用echo $?来判断,echo $?结果为0则表示运行成功,参与运算的均为数字;exco $?结果为非0,则表示参与运算的有非整数。
1)简单判断是否整数
[root@test101 tmp]# cat test.sh #例1 判断的目标是8 #!/bin/bash a=8 expr $a \* 6 &>/dev/null echo $? [root@test101 tmp]# ./test.sh 0 #expr运算成功,表示被判断的8是整数 [root@test101 tmp]# [root@test101 tmp]# cat test.sh #例2 判断目标是sre #!/bin/bash a=sre expr $a \* 6 &>/dev/null echo $? [root@test101 tmp]# ./test.sh 2 #expr运算失败,表示被判断的sre是非整数 [root@test101 tmp]#
2)判断参数是否为整数
[root@test101 tmp]# cat test.sh #!/bin/bash expr $1 + 1 >/dev/null 2>&1 if [ $? -eq 0 ] then echo Yes else echo No fi [root@test101 tmp]# [root@test101 tmp]# ./test.sh 1 #输入的1是整数 Yes [root@test101 tmp]# ./test.sh sre #输入的字符串sre不是整数 No [root@test101 tmp]#
4. expr判断文件扩展名是否符合要求
例如,要求文件扩展名须为.txt
[root@test101 tmp]# cat test.sh #!/bin/bash if expr "$1" : ".*\.txt" &>/dev/null then echo "Yes" else echo "please use .txt" fi [root@test101 tmp]# [root@test101 tmp]# ./test.sh 1.sh please use .txt [root@test101 tmp]# [root@test101 tmp]# ./test.sh 1.txt Yes [root@test101 tmp]#
5. 通过expr计算字符串的长度
1)计算指定字符串的长度
[root@test101 tmp]# cat test.sh #!/bin/bash arr="my name is sre" expr length "$arr" [root@test101 tmp]# [root@test101 tmp]# ./test.sh 14 [root@test101 tmp]#
2)筛选指定长度的字符串
例:筛选出以下语句中,字符长度大于4的单词
[root@test101 tmp]# cat test.sh #!/bin/bash arr="The past belongs to death, and that the future belongs to yourself。" for i in $arr do if [ `expr length $i` -ge 4 ] then echo $i fi done [root@test101 tmp]# [root@test101 tmp]# ./test.sh past belongs death, that future belongs yourself。 [root@test101 tmp]# [root@test101 tmp]#
6. 抓取指定字符串
1)抓取指定字符串第一次出现的位置
[root@test101 tmp]# expr index "future" t 3 [root@test101 tmp]# expr index "future" u 2 [root@test101 tmp]# [root@test101 tmp]#
2)截取指定字符串
[root@test101 tmp]# expr substr "futrue" 2 2 #截取futrue这个字符串中第2个字符开始的2个字符 ut [root@test101 tmp]#
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/135521.html