expr命令

expr命令的兩大做用:
1)四則運算;
2)字符串的操做;

一、四則運算
[tough@localhost ~]$ expr 6+2
6+2

[tough@localhost ~]$ expr 6 + 2
8

[tough@localhost ~]$ expr 6 - 2
4

[tough@localhost ~]$ expr 6 / 2
3

[tough@localhost ~]$ expr 6 * 2
expr: syntax error

[tough@localhost ~]$ expr 6 \* 2
12

[tough@localhost ~]$ expr 6 + 3 - 5
4

注意: 運算符左右都有空格 ,若是沒有空格表示是字符串鏈接
使用乘號時,必須用反斜線屏蔽其特定含義。由於shell可能會誤解顯示星號的意義。

[tough@localhost ~]$ expr 1.4 / 2
expr: non-numeric argument

[tough@localhost ~]$ echo $?
2

[tough@localhost ~]$ expr 2 / 2 
1

[tough@localhost ~]$ echo $?  
0
計算非整數,將返回錯誤,且返回碼非0。


二、字符串的操做
1)截取子串
從第7位開始,截取5位。
[tough@localhost ~]$ expr substr "Hello World" 7 5
World

 

2)提取指定字符的下標
在"123#45"中找到"#"的位置,在第4位。
[tough@localhost ~]$ expr index "123#45" "#"
4
相關文章
相關標籤/搜索