Linux命令之expr详解

1,说明:
 将EXPRESSION的值打印到标准输出。下面的空行分隔增加的优先级组
2,语法:
 EXPR表达式
 表达式说明:
    2.1,用空格隔开每一项
    2.2,用\(反斜杠)放在壳特定字符前面
    2.3,对包含空格或者其他特定字符的字符串要用引号括起来
3,例
 3.1,expr length $string

   返回$字符串字符串的长度,其中串不允许为空,否则将报错,所以可以用来判断变量是否为空

  -bash-4.1 $ string="my name is kevinMa." 
  -bash-4.1 $ expr length "$string" 
  19 
  -bash-4.1 $ echo ${#string} 
  19 
  -bash-4.1 $ xxx =""
  bash -4.1 $ expr length $xxx 
  expr:语法错误
  -bash-4.1 $ if [$? - ne 0]; then echo'$xxx is null'; fi 
  $xxx is null
  -bash-4.1 $

 3.2,expr substr $string pos len

    从$ string字符串中取出从POS位置开始长度为LEN的子字符串。如果POS或LEN为非正整数时,将返回空字符串

  -bash-4.1 $ string="0123456789" 
  -bash-4.1 $ expr substr "$string" 2 3 ##以1开始标号,必须有长度参数
  123 
  -bash-4.1 $ echo ${string:2:3}       ##以0开始标号,可以没有长度参数echo ${string:2} 
  234 
  -bash-4.1 $

 3.3,expr index $string substring

    在字符串$ string中找出substring中的字符第一次出现的位置,若找不到则返回0

  -bash-4.1 $ string="my name is kevinMa." 
  - bash -4.1 $ expr index "$string" km ## m出现在第一个位置
  1 
  -bash-4.1 $ expr index "$string" K    ##没有K字符返回0 
  0 
  -bash-4.1 $ 

 3.4,expr match $string substring

   在$string字符串中匹配substring字符串,然后返回匹配到的substring字符串的长度,若找不到则返回0

  -bash-4.1 $ echo $string 
  my name is kevinMa。
  - bash -4.1 $ expr match "$string" my.* 
  19
  -bash-4.1 $ expr match "$string" my
  2 
  -bash-4.1 $ expr match "$string" is
  0 
  -bash-4.1 $  

 3.5,整数表达式(任意操作符两端都需要有空格)

  -bash-4.1 $ a = 3 
  -bash-4.1 $ b = 4 
  -bash-4.1 $ expr $b  -  $a 
  1 
  -bash-4.1 $ expr 5%$a 
  2 
  -bash-4.1 $ expr 5 / $a 
  1 
  -bash-4.1 $ expr 10 / $a 
  3 
  -bash-4.1 $ expr $ a \ * $b 
  12

 3.6,比较操作符

  -bash-4.1 $ string="abcd" 
  -bash-4.1 $ expr "$string" = "abc"
  0 
  -bash-4.1 $ expr "$string" = "abcd" 
  1 
  -bash-4.1 $ echo $a $b 
  3 4 
  -bash-4.1 $ expr $a \> $b 
  0 
  -bash-4.1 $ expr $a \ <$b 
  1 
  -bash-4.1 $ expr $a \ * 3 = 9 
  1

 3.7,逻辑连接符号“&”与“|”

  -bash-4.1 $ echo $a 
  3 
  -bash-4.1 $ echo $b 
  4 
  -bash-4.1 $ expr "$a" "|" "$b"
  3 
  -bash-4.1 $ expr "" "|" "$b" 
  4 
  -bash-4.1 $ expr "" "&" "$b" 
  0 
  -bash-4.1 $ expr "$a" "&" "$b" 
  3 
  -bash-4.1 $

你可能感兴趣的:(Linux)