shell_脚本开发_数值运算_expr命令
expr命令
简单的计算器执行命令
可以用expr --help查看文档
#expr 是以传入参数的形式进行计算的 ,它基于空格传入参数,但是在shell里的一些元字符(*啊这类)都是有特俗含义的,需要转义
[root@localhost ~]# expr 2 + 5
7
[root@localhost ~]# expr 2 * 5
expr: 语法错误
[root@localhost ~]# expr 2 \* 5
10
[root@localhost ~]# expr 2 \/ 5
0
[root@localhost ~]# expr 5 \/ 5
1
[root@localhost ~]# expr 5 \+ 5
10
[root@localhost ~]# 求字符串长度
[root@localhost ~]# expr length 123
3
[root@localhost ~]#
[root@localhost ~]# #逻辑判断,1是真0是错
[root@localhost ~]# expr 5 \>1
expr: 语法错误
[root@localhost ~]# expr 5 \> 1
1
[root@localhost ~]# expr 5 \> 6
0
[root@localhost ~]#
expr模式匹配
expr也支持模式匹配功能
- 2个特殊符号
:冒号,计算字符串的字符数量
.* 任意的字符串重复0次或者多次 (就是匹配模式)
-
语法
expr 字符串 ":" ".*"
[root@localhost ~]# #统计文件的字符个数 [root@localhost ~]# expr yc.png ":" ".*" 6 [root@localhost ~]# expr ycc.png ":" ".c" 2 [root@localhost ~]# expr ycc.png ":" ".g" 0 [root@localhost ~]# expr ycc.png ":" ".*g" 7 [root@localhost ~]# expr ycc.png ":" ".*c" 3 [root@localhost tmp]# expr "hello.jpeg" ":" ".*"\.jpg 0 [root@localhost tmp]# expr "hello.jpeg" : .*\.jpg 0 [root@localhost tmp]# expr "hello.jpeg" : .*\.jpeg 10 [root@localhost tmp]# expr "hello.jpeg" : .*.jpeg 10 [root@localhost tmp]# expr "hello.jpeg" ":" ".*"\.jpeg #加上引号和转义方便看
-
应用实例
###eg1,执行脚本,,传入一个文件名,然后判定该文件,死否jpg图片文件 #!/bin/bash # 注意,如果写成 expr "${1}" ":" ".*"\.jpg 则会匹配出 afafajpg.gd #注意判断语句也可写成,如果是最大长度必定是结尾了晒 if [ `expr length ${1}` -eq `expr ${1} ":" ".*"\.jpg` ] if expr "${1}" ":" ".*\.jpg" &> /dev/null ###expr执行结果如果非0则真,否则为假;并把执行结果输入黑洞文件 then echo "你好,你输入的是jpg图片" else echo "抱歉,你输入的不是jpg图" fi ~ ############################################## ##eg2. 找出长度不大于5的单词 [root@localhost tmp]# cat test_expr.sh #!/bin/bash # # for vars in $* do if [ `expr length $vars` -le 5 ] then echo $vars fi done [root@localhost tmp]# sh test_expr.sh ab abc abcd abced abceef akfafafa ab abc abcd abced [root@localhost tmp]#
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!