bash shell中expr命令下几种的使用
bash shell中expr命令下几种的使用
expr在linux中是一个功能非常强大的命令。通过学习做一个小小的总结。1、计算字符串的长度。我们可以用awk中的length(s)进行计算。我们也可以用echo中的echo ${#string}进行计算,当然也可以expr中的expr length $string 求出字符串的长度。
举例
- [root@localhost shell]# string="hello,everyone my name is xiaoming"
- [root@localhost shell]# echo ${#string}
- 34
- [root@localhost shell]# expr length "$string"
- 34
- [root@localhost shell]# string="hello,everyone my name is xiaoming"
- [root@localhost shell]# expr index "$string" my
- 11
- [root@localhost shell]# expr index "$string" nihao
- 1
- [root@localhost shell]# string="hello,everyone my name is xiaoming"
- [root@localhost shell]# expr match "$string" my
- 0
- [root@localhost shell]# expr match "$string" hell.*
- 34
- [root@localhost shell]# expr match "$string" hell
- 4
- [root@localhost shell]# expr match "$string" small
- 0
- root@localhost shell]# string="hello,everyone my name is xiaoming"
- [root@localhost shell]# echo ${string:10}
- yone my name is xiaoming
- [root@localhost shell]# echo ${string:10:5}
- yone
- [root@localhost shell]# echo ${string:10:10}
- yone my na
- [root@localhost shell]# expr substr "$string" 10 5
- ryone
注意:echo ${string:10:5}和 expr substr "$string" 10 5的区别在于${string:10:5}以0开始标号而expr substr "$string" 10 5以1开始标号。
5、删除字符串和抽取字符串相似${string#substring}为删除string开头处与substring匹配的最短字符子串,而${string##substring}为删除string开头处与substring匹配的最长字符子串。 举例- [root@localhost shell]# string="20091111 readnow please"
- [root@localhost shell]# echo ${string#2*1}
- 111 readnow please
- [root@localhost shell]# string="20091111 readnow please"
- [root@localhost shell]# echo ${string##2*1}
- readnow please
- [root@localhost shell]# string="you and you with me"
- [root@localhost shell]# echo ${string/you/me}
- me and you with me
- [root@localhost shell]# string="you and you with me"
- [root@localhost shell]# echo ${string//you/me}
- me and me with me
评论暂时关闭