expr


expr在linux中 是一個功能非常強大的命令。通過學習做一個小小的總結。

1、計算字符串的長度。我們可以用awk中的length(s)進行計算。我們 也可以用echo中的echo ${#string}進行計算,當然也可以expr中的expr length $string 求出字符串的長度。
舉 例
  1. [root@localhost shell]# string="hello,everyone my name is xiaoming"
  2. [root@localhost shell]# echo ${#string}
  3. 34
  4. [root@localhost shell]# expr length "$string"
  5. 34
注意:當string字符串中有空格時必須用雙引號把$string引起來。
2、 expr中的expr index $string substring索引命令功能在字符串$string上找出substring中字符第一次出現的位置,若找不到則expr index返回0或1。
舉 例
  1. [root@localhost shell]# string="hello,everyone my name is xiaoming"
  2. [root@localhost shell]# expr index "$string" my
  3. 11
  4. [root@localhost shell]# expr index "$string" nihao
  5. 1
 
3、expr中的expr match $string substring命令在string字符串中匹配substring字符串,然后返回匹配到的substring字符串的長度,若找不到則返回0。
舉 例
  1. [root@localhost shell]# string="hello,everyone my name is xiaoming"
  2. [root@localhost shell]# expr match "$string" my
  3. 0
  4. [root@localhost shell]# expr match "$string" hell.*
  5. 34
  6. [root@localhost shell]# expr match "$string" hell
  7. 4
  8. [root@localhost shell]# expr match "$string" small
  9. 0
4、在shell中可以用{string:position}和 {string:position:length}進行對string字符串中字符的抽取。第一種是從position位置開始抽取直到字符串結束,第二 種是從position位置開始抽取長度為length的子串。而用expr中的expr substr $string $position $length同樣能實現上述功能。
舉例
  1. [root@localhost shell]# string="hello,everyone my name is xiaoming"
  2. [root@localhost shell]# echo ${string:10}
  3. yone my name is xiaoming
  4. [root@localhost shell]# echo ${string:10:5}
  5. yone
  6. [root@localhost shell]# echo ${string:10:10}
  7. yone my na
  8. [root@localhost shell]# expr substr "$string" 10 5
  9. 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匹配的最長字符子串。
舉 例
  1. [root@localhost shell]# string="20091111 readnow please"
  2. [root@localhost shell]# echo ${string#2*1}
  3. 111 readnow please
  4. [root@localhost shell]# string="20091111 readnow please"
  5. [root@localhost shell]# echo ${string##2*1}
  6. readnow please
解析:第一個為刪除2和1之間最短匹配,第二個為刪 除2和1之間的最長匹配。
6、替換子串${string/substring/replacement}表示僅替換一次 substring相配字符,而${string//substring//replacement}表示為替換所有的substring相配的子串。
舉 例
  1. [root@localhost shell]# string="you and you with me"
  2. [root@localhost shell]# echo ${string/you/me}
  3. me and you with me
  4. [root@localhost shell]# string="you and you with me"
  5. [root@localhost shell]# echo ${string//you/me}
  6. me and me with me
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM