shell_脚本开发_数值运算_expr命令

发布时间 2023-10-10 10:31:39作者: WeChat2834
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]#