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
注意:当string字符串中有空格时必须用双引号把$string引起来。
2、 expr中的expr index $string substring索引命令功能在字符串$string上找出substring中字符第一次出现的位置,若找不到则expr index返回0或1。
举 例
- [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
3、expr中的expr match $string substring命令在string字符串中匹配substring字符串,然后返回匹配到的substring字符串的长度,若找不到则返回0。
举 例
- [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
4、在shell中可以用{string:position}和 {string:position:length}进行对string字符串中字符的抽取。第一种是从position位置开始抽取直到字符串结束,第二 种是从position位置开始抽取长度为length的子串。而用expr中的expr substr $string $position $length同样能实现上述功能。
举例
- [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
解析:第一个为删除2和1之间最短匹配,第二个为删 除2和1之间的最长匹配。
6、替换子串${string/substring/replacement}表示仅替换一次 substring相配字符,而${string//substring//replacement}表示为替换所有的substring相配的子串。
举 例
- [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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)