expr命令

时间:2023-12-25 10:11:37
expr命令的兩大作用:
1)四则运算;
2)字符串的操作;

1、四则运算

[tough@localhost ~]$ expr +
+ [tough@localhost ~]$ expr + [tough@localhost ~]$ expr - [tough@localhost ~]$ expr / [tough@localhost ~]$ expr *
expr: syntax error [tough@localhost ~]$ expr \* [tough@localhost ~]$ expr + -

注意: 运算符左右都有空格 ,如果没有空格表示是字符串连接
使用乘号时,必须用反斜线屏蔽其特定含义。因为shell可能会误解显示星号的意义。

[tough@localhost ~]$ expr 1.4 /
expr: non-numeric argument [tough@localhost ~]$ echo $? [tough@localhost ~]$ expr / [tough@localhost ~]$ echo $?
计算非整数,将返回错误,且返回碼非0。

2、字符串的操作
1)截取子串

从第7位开始,截取5位。
[tough@localhost ~]$ expr substr "Hello World"
World

2)提取指定字符的下标
在"123#45"中找到"#"的位置,在第4位。

[tough@localhost ~]$ expr index "123#45" "#"