linux expr命令

在Linuxshell命令中expr虽然不是很起眼,但是它的作用是非常大的。包含:四则运算和字符串的操作。

一、先说四则运算,在Shell中四则运算不能简简单单的加减乘除,需要使用expr。expr命令只能用于整数值,一般格式为:

expr arg1 operatorarg2

注意:

1、运算符左右都有空格运算符左右都有空格,如果没有空格表示是字符串连接)

2、使用乘号时,必须用反斜线屏蔽其特定含义。因为shell可能会误解显示星号的意义。

$expr 30 \* 3

90

3、如果试图计算非整数,将返回错误。

$rr=1.1

$expr $rr + 1

expr: non-numericargument

4、expr默认是直接把运算结果输出到控制台,如果想赋值可以使用”`“

示例:

[root@zq-crmtest-20423tmp]# expr 10 + 10

20

[root@zq-crmtest-20423tmp]# expr 1500 + 900

2500

[root@zq-crmtest-20423tmp]# expr 30 / 3

10

[root@zq-crmtest-20423tmp]# expr 30 / 3 / 2

5

[root@zq-crmtest-20423tmp]# a=11

[root@zq-crmtest-20423tmp]# b=`expr $a - 1`

[root@zq-crmtest-20423tmp]# echo $b

10

补充:对于四则运算,最好用$(())代替expr,效率更高,而且运算符两边不用空格

[root@zq-crmtest-20423tmp]# count=1

[root@zq-crmtest-20423tmp]# count=$(($count+1))

[root@zq-crmtest-20423tmp]# echo $count

 

对于四则运算,也可以使用$[],运算符两边也不用空格

[root@zq-crmtest-20423tmp]# var=$[1+5]

[root@zq-crmtest-20423tmp]# echo $var  //6

 

[root@zq-crmtest-20423tmp]# count=1

[root@zq-crmtest-20423tmp]# var=$[$count+1]

[root@zq-crmtest-20423tmp]# echo $var

 

二、expr的字符串操作:

1、返回字符串长度:expr length  字串

[root@zq-crmtest-20423tmp]# expr length "hello world"

11

2返回 String1 中包含 String2 中任意字符的第一个位置 expr indexString1 String2

[root@zq-crmtest-20423tmp]# expr index "abc" "b"

2

3提取字符串的子串:expr substr 内容 起始位置 终点位置,

[root@zq-crmtest-20423tmp]# expr substr "this is a test" 3 5

is is

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赶路人儿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值